Change Image Source using JQuery
Landing here means that you probably want to change image source using jquery.
Tell me more about your problem, you want a user to click on a button and the image should get change upon the event happening or you want an image to get change on scrolling down to a certain amount of web page.
You can read a separate guide about the scrolling event handling in this guide.
Coming back to the problem and solution of it. We have found 2 major solutions to change the image source using jquery.
Possible Solution 1 – Change Image Source using JQuery
You can easily use the jquery default function attr().
Consider that your img tag has an id named as “imageID1”
1 |
<img id="imageID1" src="first_image.jpg"/> |
Now using jquery you can easily change the image source.
1 |
$("#imageID1").attr("src","second_image.jpg"); |
The $ (dollar sign) is the jquery object which initiate all of jquery functions.
#imageID1 is the id of our img element which we want to change. attr() is jquery function which accept two main paramenters. first parameter should be the type of attribute and the second parameter should be the value of that attribute.
Using src as first parameter and second_image.jpg as second parameter.
Change the image onclick function – jQuery
1 2 3 4 5 |
$('#imageID1').on({ 'click': function(){ $('#imageID1').attr('src','second_image.jpg'); } }); |
You can also use the below code for onclick function
1 2 3 |
$.('#imageID1').addEventListener('click', function () { $('#imageID1').attr('src','second_image.jpg'); }); |
but don’t limited to them, here is one more option.
1 2 3 |
$.('#imageID1').click( function () { $('#imageID1').attr('src','second_image.jpg'); }); |
Final Words
This is it to change image source using jquery. You can give try to these codes if you still face any problem just don’t hesitate to start a conversation in comment section. I will try my best to answer your questions one by one.