Home > OS >  Javascript click image to replace another image with the clicked src
Javascript click image to replace another image with the clicked src

Time:07-26

I'm trying to make a simple operation of loading the page with a large image at the top and a row of smaller gallery images at the bottom so that clicking on a smaller image will place it into the larger top container.

I'm using PHP loaded urls in my site so I've replaced them here with placeholder images, but the problem persists and I'm pretty sure it has to do with how I'm declaring the css work in my javascript because clicking on the small images definitely performs the action but the source doesn't seem to load.

What exactly have I messed up here?

    $('.gallery__source').on('click', function(){
        console.log('clicked');
        var src = $(this).children('img').attr('src');  
        $('.itempage_wrapper_plain').css('background-image','url(src)');
    });
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
        integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>

<div  style="background-image:url('https://loremflickr.com/320/240/dog'); border-radius: 25px 0px 0px 0px; height:300px; width:300px;">
</div>

<div >
    <img style="padding:10px;" src="https://loremflickr.com/320/240">
</div>

CodePudding user response:

This doesn't actually use the src variable:

'url(src)'

It's just a string literal. You can concatenate the variable:

'url('   src   ')'

Or use a template literal:

`url(${src})`

CodePudding user response:

$(".gallery__source").on("click", function() {
  console.log("clicked");
  var src = $(this)
    .children("img")
    .attr("src");
  $(".itempage_wrapper_plain").css("background-image", "url("   src   ")"); // this needs to change to string concatenation
});
  • Related