Reputation: 4239
I am trying to add an image on top of multiple divs
when the user clicks a button.
so
----------
| |
----------
----------
| |
----------
----------
| |
----------
----------
| |
----------
button
after click a button
oo means image
----------
|oo |
----------
----------
| |
----------
----------
|oo |
----------
----------
| |
----------
I am not sure how to accomplish this. Any hints would be appreciated. Thanks.
Upvotes: 0
Views: 400
Reputation: 9154
I'm going to go with a different assumption than "every other one". Here's a jsfiddle for demonstration
This solution allows for any arbitrary divs to gain an image upon button click, so long as you've identified them or tagged them in some way. So...
If your DOM identified which elements should gain a picture through some class naming:
<div class="yes"> </div>
<div class="no"> </div>
<div class="yes"> </div>
<div class="no"> </div>
<button id="button">Click me</button>
And with some CSS like follows:
.picture{
background-image: url("http://lorempixel.com/200/100/")
}
All you need is a function like so:
$('#button').on('click', function() {
$('.yes').addClass("picture");
});
Upvotes: 2
Reputation: 21386
You may better use <table>
to get a stable layout like;
<table>
<tr><td>Row with Index #0</td></tr>
<tr><td>Row with Index #1</td></tr>
<tr><td>Row with Index #2</td></tr>
<tr><td>Row with Index #3</td></tr>
</table>
And I think you are looking for a solution something like;
$('#mybutton').click(function() {
$("tr:odd").css("background-image", "url('http://jsfiddle.net/favicon.png')");
});
Here is a working Live Demo.
Upvotes: 0
Reputation: 87073
I assume following html:
HTML
<div class="hasimg"></div>
<div class="hasimg"></div>
<div class="hasimg"></div>
<div class="hasimg"></div>
Then on button click try this:
jQuery
$('button').on('click', function() {
$('div.hasimg:nth-child(2n+1)').append('<img src="" width="" height="">');
});
Here, 'div.hasimg:nth-child(2n+1)'
will select each odd div
with class=hasimg
.
To make that image top you can use some CSS like following:
CSS
div.hasimg {
position: relative
}
div.hasimg img {
z-index: 100;
position: absolute;
/* and necessary config */
}
Just modify CSS
as your need.
Upvotes: 1