-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
  • 204,283
  • 31
  • 260
  • 272
Boy Pasmo
  • 8,021
  • 13
  • 42
  • 67

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,899
  • 5
  • 77
  • 90
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
  • 204,283
  • 31
  • 260
  • 272
0

You need to wait for the DOM to fully load.

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

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

Eric Goncalves
  • 5,253
  • 4
  • 35
  • 59
0

Try this

JS CODE

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