Home > other >  How can I change the image click destination image src?
How can I change the image click destination image src?

Time:09-22

I would like to change the src of each image when I click the image with J-Query. I want to change the src value using attr. I want to change it to 1_on.png when I click 1_off.png, and change it to 2_on.png when I click 2_off.png. I want to change it to off when I click the image and click it again. How can I do that?

<img alt="" src="img/1_off.png" id="pic">
 <img alt="" src="img/2_off.png" id="pic">
 <img alt="" src="img/3_off.png" id="pic">
 <img alt="" src="img/4_off.png" id="pic">
 <img alt="" src="img/5_off.png" id="pic">

CodePudding user response:

You can do this using below approach, But first change your id into class because there only one id with same in a single document. you your code would be like this.

<img alt="" src="img/1_off.png"  data-toggle="1_on.png" data-active="on" onclick="activate_toggle(this)">
<img alt="" src="img/2_off.png"  data-toggle="2_on.png" data-active="on" onclick="activate_togle(this)">
<img alt="" src="img/3_off.png"  data-toggle="3_on.png" data-active="on" onclick="activate_togle(this)">
<img alt="" src="img/4_off.png"  data-toggle="4_on.png" data-active="on" onclick="activate_togle(this)">
<img alt="" src="img/5_off.png"  data-toggle="5_on.png" data-active="on" onclick="activate_togle(this)">


<script>
function activate_toggle(obj){
 let output_toggle=$(obj).data('toggle');
 if($(obj).data('active')=='on'){
   var num = output_toggle.replace(/[^0-9]/g, '');
  let change_toggle=num '_off.png';
    $(obj).data('toggle',change_toggle);
    $(obj).data('active','off');
 }else{
   var num = output_toggle.replace(/[^0-9]/g, '');
   let change_toggle=num '_on.png';
    $(obj).data('toggle',change_toggle);
   $(obj).data('active','on');
 }
 $(obj).attr('src','img/' output_toggle);
}
</script>
  • Related