Change image with jQuery

I have an html page that uses jQuery-ui accordion. Now I have to add an image to this page 2, which should change depending on the active section. How can i do this?

HTML:

<div id="acc"> <h1>Something</h1> <div>Text text text</div> <h1>Something too</h1> <div>Text2 text2 text2</div> </div> <div id="pic"> <img class="change" src="1.png"/> <img class="change" src="2.png"/> </div> 

JS:

 $(document).ready(function() { $("#acc").accordion({ change: function(event, ui) { /* I'm think something need here */ } }); }); 
+4
source share
4 answers

This script will show the first img for the first panel, the second img for the second panel, etc.

 jQuery(function($) { $("#acc").accordion({ change: function(event, ui) { var index = $(ui.newContent).index("#acc>div"); $("#pic .change") // Hide all .hide() // Find the right image .eq(index) // Display this image .show(); } }); }); 
+4
source

HTML:

 <div id="pic"> <img id="change1" class="change" src="1.png"/> <img id="change2" class="change" src="2.png"/> </div> 

JS (I assume that in your conditions - suppose you need a different image for the displayed accordion)

 $(document).ready(function() { $("#acc").accordion({ change: function(event, ui) { if(ui.newheader == "A header") { $("#change1").attr("src", "new1.png"); $("#change2").attr("src", "new2.png"); } else if(ui.newHeader == "Another header") { $("#change1").attr("src", "1.png"); $("#change2").attr("src", "2.png"); } } }); }); 

If instead you want to switch between two images:

 $(document).ready(function() { $("#acc").accordion({ change: function(event, ui) { if(ui.newheader == "A header") { $("#change1").hide(); $("#change2").show(); } else if(ui.newHeader == "Another header") { $("#change1").show(); $("#change2").hide(); } } }); }); 
+5
source

You're right; you need to put it in the accordion change event.

You can change the image as follows:

 $('.change').attr('src', someUrl); 
0
source

n my experience with image with changing div usage:

HTML:

 <div id="pic"><img id="1" src=""></div> 

and jQuery:

var url = "";

 $(document).ready(function() { $("#acc").accordion({ change: function(event, ui) { var url = ""; /* set immage url here */ $('1').attr("src", url); } }); }); 

and with this u can have as many images as possible, such as u, like changing in the same div

PS.

If you don't like your img beeing empty at boot time, you can use

display: no;

css attribute

and then use .show (); first click function

0
source

Source: https://habr.com/ru/post/1308360/


All Articles