user1347219
user1347219

Reputation: 291

javascript if else click event

I am trying to add an if else statement to the below

$('#togglediv4').click(function(e){
     e.preventDefault();
    $('#link4').attr('src','images/contact_link_clicked.png');
});

I want the image to change back to the original one if there is no click event otherwise all links once clicked will remain stuck on the new image.

Therefore if image is not clicked I want to show the original image.

$('#link4').attr('src','images/contact_link_original.png');

Upvotes: 1

Views: 797

Answers (4)

cowls
cowls

Reputation: 24334

You should just set the src attribute of the original <img> tag to: mages/contact_link_original.png

Then add the click event as above.

By default when your div hasnt been clicked it will contain the original image.

EDIT: based on your comment I would do the following:

  • Add a class to all the images
  • When any image is clicked change the src attr back to the original on ALL images with that class. (You can use $('.imgClass'))
  • Then update the image that was clicked with the new image.

Upvotes: 1

Chris Laarman
Chris Laarman

Reputation: 1589

I think you are looking for something like this:

$('#togglediv4').click(function(e){
    e.preventDefault();
    if ($('#link4').attr('src') == 'images/contact_link_original.png') {
        $('#link4').attr('src','images/contact_link_clicked.png');
    }       
});

Upvotes: 0

Ram
Ram

Reputation: 144669

Use attr callback function and ternary operator.

$('#togglediv4').click(function(e){
     e.preventDefault();
     $('#link4').attr('src',function(i, src){
          return src === 'images/contact_link_original.png'
          ? 'images/contact_link_clicked.png'
          : 'images/contact_link_original.png'
     });
});

Upvotes: 2

Gareth
Gareth

Reputation: 5719

I may not be understanding your question correctly, but it looks to me like you need to use the mousedown and mouseup events instead of click:

$('#togglediv4').mousedown(function(e){
    e.preventDefault();
    $('#link4').attr('src','images/contact_link_clicked.png');
}).mouseup(function(e){
    e.preventDefault();
    $('#link4').attr('src','images/contact_link_original.png');
});

Upvotes: 0

Related Questions