Anu Upadhyayula
Anu Upadhyayula

Reputation: 1

how to detect which image is clicked in a list using only one click function in jquery

I want to use only a one-click function to change the source path for the multiple images. each click should be specific to each image. For example: if I click on one image it should change the src path for that image only. Please help me with this. Here is the code:

$(document).ready(function () {

  $('.n_daynite').click(function () {
    $('.n_daynite').attr('src', "img/BM_DayNight_v.png");
  });

  $('.n_glamour').click(function () {
    $('.n_glamour').attr('src', "img/BM_Glamour_v.png");
  });

  $('.n_GQ').click(function () {
    $('.n_GQ').attr('src', "img/BM_GQ_v.png");
  });

  $('.n_Maxim').click(function () {
    $('.n_Maxim').attr('src', "img/BM_Maxim_v.png");
  });

  $('.n_Popular').click(function () {
    $('.n_Popular').attr('src', "img/BM_Popular_v.png");
  });

  $('.n_Preferred').click(function () {
    $('.n_Preferred').attr('src', "img/BM_Preffered_v.png");
  });

  $('.n_TChad').click(function () {
    $('.n_TChad').attr('src', "img/BM_TChad_v.png");
  });

});

Upvotes: 0

Views: 67

Answers (4)

Jobelle
Jobelle

Reputation: 2834

 $(document).ready(function () {

    $('img').click(function () {

        var newSRC = Replace($(this).attr('class'),"n_","");

        newSRC = "img/BM_" + $(this).attr('class') + "_v.png";

        $(this).attr('src', newSRC)

    });


});

Upvotes: 0

Bhushan Kawadkar
Bhushan Kawadkar

Reputation: 28513

Try this : You can put selector for all images with class name start with n_ using jquery start with selector. Use class name to create new src path and assign it to image.

NOTE :- this solution is with assumption that img will have only one class name.

//use start with selector for image with class starting with n_
$('img[class^="n_"]').click(function () {
    var class = $(this).attr('class');
    class = class.replace('n_','');
    //create new source path of image
    var new srcPath = "img/IBM_" + class + "_v.png";
    $(this).attr('src', srcPath);
});

Upvotes: 1

Veshraj Joshi
Veshraj Joshi

Reputation: 3579

make use of same class like

<img src="url_to_image" class="n_daynite" image-url="url_to_image_of_replacing_image"/>
// image-url is new attribute and will help to store the url of new image

and make use of

this

like below

//dedication method 
$('.n_daynite').click(function(){
   $(this).attr('src',$(this).attr('image-url'));
});

I think this will be all dynamic

Upvotes: 0

Amar Singh
Amar Singh

Reputation: 5622

Give same class to all the images (say class=yoyo)

and use this code :

$('.yoyo').click(function () {
$(this).attr('src', "img/BM_DayNight_v.png");
  /*_add any src path to the clicked image_*/
});

Upvotes: 0

Related Questions