Question

I'm attempting to replace a featured image on a page with any image clicked on in the .gallery div. This will be used on multiple pages in my site so I'd like it to be agnostic of the number of images in the gallery (as that will vary) and where in the gallery the image falls.

Is there a way to simply grab the src of the clicked image and replace the src of another image with it? I've dug through a few other topics here on Stack Overflow and pieced together the following code based on them, but it doesn't seem to be working yet. Am I headed in the correct direction?

$(".galleryimg").click(function(){
    var r1 = $(this).attr("src");
    $('#selected-image').attr("src", r1).replace(r1);
});
Was it helpful?

Solution

This should work:

$(".galleryimg").click(function(){
    var r1 = $(this).attr("src");
    $('#selected-image').attr("src", r1);
});

If it doesn't, there is an error somewhere else in your code or DOM.

Here is a brief demo

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top