Chandler Muriel Bing
Chandler Muriel Bing

Reputation: 11

How do change only a path from image source with jQuery?

I'm trying to add dark mode function to my website and everything is fine with divs and other objects but I cannot change the only the path of images.

I have 2 folders for dark & regular images and each folder contains same files with same names but only edited for dark and regular mode of website, so I want to change the src to ../assets/imgs/regular/filename.jpg to ../assets/imgs/dark/samefilename.jpg.

I'm so much a newbie so please keep your answers simple.

Upvotes: 0

Views: 1404

Answers (3)

Cankan
Cankan

Reputation: 37

select the image tag, and change src attribute with Jquery .attr()

$("img").attr("src","your path");

Upvotes: 0

Sandeep
Sandeep

Reputation: 65

It sounds like you need to

  • Loop over your images
  • Pull each SRC attribute
  • Do a regex find/replace

i.e. something like this for setting to dark mode:

jQuery('img').each(function(){
    jQuery(this).attr('src', jQuery(this).attr('src').replace(/assets\/imgs\/regular/i, 'assets/imgs/dark'))
});

Upvotes: 1

Just Alex
Just Alex

Reputation: 457

If you want to do this with jQuery (although you can also do it with vanilla js), you should use jQuery's attr() function.

For example, if your image has an id of myImage, simply write :

$("#myImage").attr('src', '../assets/imgs/dark/samefilename.jpg');

This will change the path from your regular image to a dark one.

But I assume you also want it to revert back once you turn off your dark mode.

So adding if-else here is perfect. For example :

$("#darkModeButton").on('click',function(){

    if($("#myImage").attr('src') == '../assets/imgs/regular/filename.jpg'){

        $("#myImage").attr('src','../assets/imgs/dark/samefilename.jpg');

    }

    else {

        $("#myImage").attr('src','../assets/imgs/regular/filename.jpg');

    }        

}

This was just a dummy example, I assume you have more then one image that you want to replace with a dark one. :)

Hope I helped even a little bit.

Upvotes: 0

Related Questions