Click here to Skip to main content
15,897,891 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi , iam trying to change the source of an image when a link is clicked using jquery but the image is not changing so what is wrong ?
This is my code:
XML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Untitled Page</title>
      <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
      <script type="text/javascript">
          $(document).ready(function() {
               $('a').click(function(){
               $('img').attr({ src: 'Tulips.jpeg', alt: 'cover2' });

          });
      });
</script>

</head>
<body>
<a  href=""   > click me</a>
<img src="Penguins.jpg" alt="cover1" />
</body>
</html>
Posted

Friend you are going to laugh when you know the mistake.
Actually you used click me so whenever you click on click me you jquery is executed but due to href="" the page is reloaded and you think that query did not work.

For resolving it you need to replace href="" with href="#" and your code will start working.
 
Share this answer
 
Hi,

The correct solution is to add return false from your click event. This cancels the event and the page does not refresh.

$(document).ready(function() {
    $('a').click(function(){
        $('img').attr({ src: 'Tulips.jpeg', alt: 'cover2' });
        return false;
    });
});


Note that you should not set your href to '#' as this results in the page scrolling to the top when the link is clicked.
 
Share this answer
 
Comments
mhamad zarif 20-Apr-11 3:05am    
Thanks for your help.It is working great !

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900