Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
54
rated 0 times [  60] [ 6]  / answers: 1 / hits: 31584  / 13 Years ago, wed, january 4, 2012, 12:00:00

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?


More From » jquery

 Answers
12

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.


[#88231] Tuesday, January 3, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
meadowe

Total Points: 0
Total Questions: 97
Total Answers: 97

Location: Laos
Member since Fri, Sep 11, 2020
4 Years ago
;