-3
<html>
<body>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>  
<script type="text/javascript">
$('img').click(function(){
    var getTitle = $(this).attr('alt');
    alert(getTitle)
});
</script>
</head>
<body>
<img src="http://localhost/wordpress/wp-content/uploads/2013/02/chair-228x300.jpg" alt="alt" width="228" height="300" class="size-medium wp-image-92" /> 
</body>
</html>

This will basically display the alt attribute of the image in a popup once clicked but it seems not working. What am I missing? Please help.

j08691
  • 197,815
  • 30
  • 248
  • 265
Boy Pasmo
  • 7,471
  • 11
  • 39
  • 60

4 Answers4

3

The DOM is not ready to be manipulated/accessed when your code executes. Use the document.ready shortcut:

$(function(){
    $('img').click(function(){
        var getTitle = $(this).attr('alt');
        alert(getTitle)
    });
});
Alex
  • 34,121
  • 5
  • 74
  • 88
1

Wrap your jQuery in a document ready call.

$(document).ready(function() {
    $('img').click(function(){
        var getTitle = $(this).attr('alt');
        alert(getTitle);
    });
});

You're executing your code before the actual elements you want to apply it to have been loaded.

j08691
  • 197,815
  • 30
  • 248
  • 265
0

You need to wait for the DOM to fully load.

   $(function() {
         // your code goes here
    });

example: http://jsfiddle.net/4Y6sL/

Eric Goncalves
  • 5,123
  • 4
  • 34
  • 59
0

Try this

JS CODE

$(function(){
   $('img').on('click', function(){
    var getTitle = $(this).attr('alt');
    alert(getTitle)
   });
});
Codegiant
  • 2,040
  • 1
  • 20
  • 30