Raouf Athar
Raouf Athar

Reputation: 1813

Change CSS position of each element in a DIV using JS or JQuery

I have a Div with position:relative which contains "one or more" images inside it with postion:absolute with some top and left values. I need to toggle the position attribute of ALL THE IMAGES at a time between Absolute and Auto/Relative with a button using JS or JQuery. Is there any way to work with all these child IMAGES at a time?

Upvotes: 1

Views: 1633

Answers (3)

Richard Neil Ilagan
Richard Neil Ilagan

Reputation: 14747

This would be best achieved using both CSS rules (as in CSS rules, not JS assigned inline styles) and jQuery's .toggleClass() method.

If you've got markup like the following:

<div id='foo'>
    <img />
    <img />
</div>

and CSS like the following:

div#foo { position:relative; }
div#foo img { position:relative; }
div#foo img.absolute { position:absolute; }

You can easily toggle that the IMGs' position rule using something like

$('button').click(function() {
    $('div#foo img').toggleClass('absolute');
});

Upvotes: 1

Sotiris
Sotiris

Reputation: 40066

try the following:

html

<div class="wrapper">
    <img src="http://dummyimage.com/15x15/000/fff" class='absPosition'>
</div>
<input type="button" value="change position">

css

.wrapper {
    height:300px;
    position:relative;
}
.absPosition {
    position:absolute;
    bottom:0;
}

jQuery

$(":button").click(function() {
    $("img").toggleClass("absPosition")
});

Demo: http://jsfiddle.net/ZRDdB/

Upvotes: 2

CodingIntrigue
CodingIntrigue

Reputation: 78535

Just use a jQuery selector which encompasses all of the images within your div. If, for example, your div had an id of "divId" then to set the position to relative of all the images within that div, you would use:

$(document).ready(function() {
  $("#button").click(function() {
    $("#divId img").css("position", "relative")
  });
});

Upvotes: 2

Related Questions