Javascript onClick change background picture of div

31,128

Solution 1

Avoid putting JS in your HTML code. Use unobtrusive event listeners. They are very easy in jQuery:

$('#clickMe').on('click', function() {
    $('#changeMe').css('background-image', 'url(http://placehold.it/200x200/ff0000)');
})

See this Fiddle.

Solution 2

Try this:

<script type="text/javascript">
    function showP(pic) { 
        document.getElementById('sp').style.background = 'url(' + pic + ')';
    };
</script>

<a onclick="showP('/assets/castle.png')">
    <im  src="/assets/castle.png" width="50px" height="50px" />
</a>

You needed to pass a string to the showP function in the onclick handler, which should be in quotes. You're passing a string into the function, which is in the pic variable being passed into the function. You want that string variable's value to be concatenated with the URL rule for the background style.

Share:
31,128
barerd
Author by

barerd

I am an anesthesiologist. Everything else is a hobby.

Updated on January 13, 2021

Comments

  • barerd
    barerd over 3 years

    My ultimate goal is to change the background of a div through clicking on the sampla picture.

    First I wrote this:

    <a onclick="document.getElementById('sp').style.background="url('/assets/castle.png')"">...<a>
    

    but it didn't work. I noticed that the problem was usage of multiple " and '. So put the function into a script tag:

    <script type="text/javascript">
        var pic="";
        function showP(pic) { document.getElementById('sp').style.background='url(pic)';};
    </script>
    
    <a onclick="showP(/assets/castle.png)"><img src="/assets/castle.png" width="50px" height="50px"></a>
    

    As supposed by seeing /assets dir, this is a rails app. I also tried o use jQuery selectors like $("#sp").css() or dropping the variable altogether and trying the function as:

    function showp1() { document.getElementById('sp').style.cssText='background: transparent url(/assets/castle.png) no-repeat 0 0;'}
    

    to try out solutions proposed in questions with similar titles but none did work. Whatever I try, on the html source, the portion showP(/assets/castle.png)" below is marked red:

    <a onclick="showP(/assets/castle.png)"><img src="/assets/castle.png" width="50px" height="50px"></a>
    

    Are there any suggestions?

    • Sikshya Maharjan
      Sikshya Maharjan over 12 years
      I suggest making, and then linking to, a JS Fiddle demo that reproduces your use-case (in brief) and problem, and also incorporating the jquery tag, as you seem to be using it.
  • barerd
    barerd over 12 years
    I tried every one's solution and none of them worked. I tried on jsFiddle with jQuery 1.7.1 and Brendan's and your solutions worked there. As Brendan's code is heavier, I prefer yours. Can you check the page at the supposed page and tell me the problem with the code? By checking the page source you can verify that jQuery 1.7.1 is loaded and another jQuery code is working.
  • Ansel Santosa
    Ansel Santosa over 12 years
    Running jQuery version on your page is reporting as 1.4.2. Try this: $('img').click(function() { $('#sp').css('background-image', 'url(' + $(this).attr('src') + ')'); });
  • barerd
    barerd over 12 years
    Thank you for making me recall the use of " + pic + " but this didn't work.
  • barerd
    barerd over 12 years
    I deleted the jQuery.min1.4.2 file and tried both of your solutions. They didn't work. I prepared a fiddle. It's not working either. Can you check that? I added the whole javascript code with the ...first-and-second-carousel.. stuff because I thought that or the syntax of the javascript might be the reason.
  • Ansel Santosa
    Ansel Santosa over 12 years
    Updated Fiddle. That just wasn't working because there was an error thrown at .jc() before the listener was attached. Make sure you are checking your JS Console for errors.
  • barerd
    barerd over 12 years
    You are right on that. I separated the javascript functions into a user.js file and firebug didn't show any errors. Maybe you noticed that the page source still marks the "javascript:;"" part red. Any idea, what may cause this error? by the way, sorry for the 10-15 min delays but I'm trying the solutions out in jsFiddle and my page.
  • Ansel Santosa
    Ansel Santosa over 12 years
    You could try <a href="javascript:void(0);" and see if it likes that better but it shouldn't be necessary and I don't see why it would be causing any problems. Worse case scenario, go to: <a href="#" it'll make the page jump to the top when you click it but it is definitely valid.
  • barerd
    barerd over 12 years
    # does not cause the page to jump to the top. So maybe link is not functioning. The source is <li style="float: left; list-style: none outside none;" class="jc-item jc-item-h><a href="#" id="castle"><img src="/assets/castle.png" width="50px" height="50px" /></a></li>. Anyway, I'm going to accept your answer since you showed all possible ways with jQuery. I'd be glad if sth comes up to your mind about the link problem.
  • Ansel Santosa
    Ansel Santosa over 12 years
    That all looks valid to me. It might be an issue with the browser. I would run the page through the W3C validator to determine whether it's the code or the browser at fault.
  • barerd
    barerd over 12 years
    Just to inform, after changing the <img /> tag to <img></img>, the code worked. Don't know the reason but nevermind:)