Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the image source using jQuery

My DOM looks like this:

<div id="d1">    <div class="c1">             <a href="#"><img src="img1_on.gif"></a>             <a href="#"><img src="img2_on.gif"></a>    </div> </div> 

When someone clicks on an image, I want the image src to change to <img src="imgx_off.gif"> where x represents the image number 1 or 2.

Is this possible or do I have to use CSS to change the images?

like image 989
user67033 Avatar asked Feb 16 '09 19:02

user67033


People also ask

How do I change the source of an image in JavaScript?

Change the Source of an Image Using the src Property in JavaScript. To change the source or src of an image, you need to add an id or class to the image tag. You can get the image element using the name of the id or class , and you can change the source or src of the image using the src property.

How do I change an image source in HTML?

You can change an HTML image src attribute programatically by using JavaScript. First, you need to grab the HTML element by using JavaScript element selector methods like getElementById() or querySelector() and assign the element to a variable.

How can add image in HTML using jQuery?

With jQuery, you can dynamically create a new image element and append it at the end of the DOM container using the . append() method. This is demonstrated below: jQuery.

How add src attribute in jQuery?

Answer: Use the jQuery attr() Method You can use the attr() method to change the image source (i.e. the src attribute of the <img> tag) in jQuery. The following example will change the image src when you clicks on the image.


1 Answers

You can use jQuery's attr() function. For example, if your img tag has an id attribute of 'my_image', you would do this:

<img id="my_image" src="first.jpg"/> 

Then you can change the src of your image with jQuery like this:

$("#my_image").attr("src","second.jpg"); 

To attach this to a click event, you could write:

$('#my_image').on({     'click': function(){         $('#my_image').attr('src','second.jpg');     } }); 

To rotate the image, you could do this:

$('img').on({     'click': function() {          var src = ($(this).attr('src') === 'img1_on.jpg')             ? 'img2_on.jpg'             : 'img1_on.jpg';          $(this).attr('src', src);     } }); 
like image 109
jonstjohn Avatar answered Nov 23 '22 15:11

jonstjohn