Skip to content Skip to sidebar Skip to footer

Javascript Onclick Change Background Picture Of Div

My ultimate goal is to change the background of a div through clicking on the sampla picture. First I wrote this: ).on('click', function() { $('#changeMe').css('background-image', 'url(http://placehold.it/200x200/ff0000)'); })

See this Fiddle.

Solution 2:

Try this:

<scripttype="text/javascript">functionshowP(pic) { 
        document.getElementById('sp').style.background = 'url(' + pic + ')';
    };
</script><aonclick="showP('/assets/castle.png')"><imsrc="/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.

Solution 3:

the background image URL does not require quotes. Try:

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

Solution 4:

As others have said, you do seem to have an issue with quotes. You can check out my working example on jsFiddle.

Post a Comment for "Javascript Onclick Change Background Picture Of Div"