Reputation: 305
In below example I want to rotate elements using insertBefore, I mean every time I click the last object should be moved to first using insertBefore.
Here is simple example,
$elems = $('.parent').find('div');
$('body').click(function() {
$elems = $elems;
$elems.eq(4).insertBefore($elems.eq(0))
console.log('clicked');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
</div>
As you can see after clicking first time, every single time same elements gets referenced and inserted before. Is it possible to use reference dom with same object? As this is really simplified example of complex problem, and it would help a lot if I can use variable instead of using jQuery selector every time.
Upvotes: 0
Views: 34
Reputation: 9634
If you want to avoid additional selections inside the DOM, than you should update your jQuery selection (array) inside the script this way (or similar):
$elems = $('.parent div');
function insertElement(selection, indexFrom, indexTo) {
selection.eq(indexFrom).insertBefore(selection.eq(indexTo));
selection.splice(indexTo, 0, selection.splice(indexFrom, 1)[0]);
};
$('body').click(function() {
insertElement($elems, $elems.length-1, 0);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
</div>
Also on JSFiddle.
For moving elements inside JS array more info at Move an array element from one array position to another.
Upvotes: 1
Reputation: 18123
I don't know why you need the object to be outside of the click function.
So here is a solution:
$('body').click(function() {
$('.parent div:last').prependTo( $('.parent') );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
</div>
To make that work, I've made an object of .parent
not .parent div
:
var par = $('.parent');
$('body').click(function() {
par.find('div:last').prependTo( par );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
</div>
Upvotes: 1