in a page i've got different divs elements with the same class
<div id="masterdiv">
<div class="a"></div>
<div class="a"></div>
<div class="a"></div>
<div class="a"></div>
<div class="a"></div>
<div class="a"></div>
<div class="a"></div>
<div class="a"></div>
<div class="a"></div>
<div class="a"></div>
<div>
with a setTimeout i want to take three elements for time do some action with them.
i tried with the slice function:
var elements = $("#masterdiv").find('.a');
var t = setInterval(function () {
var currentElements = elements.slice(points.f, points.l);
/* where points.f = 0 and points.l = 3 */
/* do something with currentElements then increment points.f and points.l +1 */
}, xinterval );
But there's a problem, at a certain time my code will reach a .slice(8,10) / .slice(9,11) and a in a selection of 11 divs.
So in these cases (point.l > elements.length()) i want select the first divs instead of the exceeded ones:
In the case of .slice(8,10) i want to select instead of the
inexistent div '10' the div 0 with the 8,9 divs .
In the case of .slice(9,11) i want to select instead of the
inexistent divs '10','11' the div 0,1 with the 9 div.
How can i accomplish this? Can i do it with slice or should i use another function?
Thanks in advance for all the help.
An alternative, would be to use the pop() and push() array functions like this:
var $elements = $("#masterdiv").find('.a');
// Convert to native Array
var elements = Array.prototype.slice.apply($elements);
var t = setInterval(function () {
elements.slice(points.f,points.l).forEach(function(el){
// do something on the element...
$(el).addClass('debug');
});
elements.push(elements.shift()); // Re-arrange elements array for loop
}, xinterval );
Here's the codepen demo: http://codepen.io/kostasx/pen/mRVzqQ?editors=0010
you can increment your variable like this,
var elements = $("#masterdiv").find('.a');
/* where points.f = 0 and points.l = 3 */
var t = setInterval(function () {
var currentElements;
if(points.l > elements.length && points.f<=elements.length){
tempArr1 = elements.slice(points.f);
tempVar = points.l % elements.length;
tempArr2 = elements.slice(0,tempVar);
currentElements = [...tempArr1,...tempArr2];
}
else{
currentElements = elements.slice(points.f, points.l);
}
/* do something with currentElements then increment points.f and points.l +1 */
}, xinterval );
I have not covered edge cases,please find yourself ;)
Related
I tried to set the same class imagens-giratorias to two elements or to set imagens-giratorias and imagens-giratorias-2. The class worked in first element, and the same class stopped of animating in the second element.
[I provide the JSFiddle at the end.]
Check the #rafaelcastrocouto's original code at https://stackoverflow.com/a/59524483/8041366. If you prefer reading the complete code here, here is the code taken from there, but with a bit modified:
var counter = 1;
var div = document.querySelector('.imagens-giratorias');
var imagens = document.querySelectorAll('.imagens-giratorias img');
var showNext = function () {
counter++;
if (counter > 3) counter = 1;
div.classList.remove('imagem1', 'imagem2', 'imagem3')
div.classList.add('imagem'+counter);
};
for (var img of imagens) {
img.addEventListener('animationend', showNext);
}
And small CSS snippet:
<div class="section-2">
<div class="item-2">
<div class="imagens-giratorias imagem1">
</div>
</div>
</div>
<div class="section-3">
<div class="item-2">
<div class="imagens-giratorias imagem1">
</div>
</div>
Or
<div class="section-3">
<div class="item-2">
<div class="imagens-giratorias-2 imagem1">
</div>
</div>
1st solution, that same original code above I am referring.
2nd solution:
var div = document.querySelector('.imagens-giratorias, .imagens-giratorias-2');
var imagens = document.querySelectorAll('.imagens-giratorias img, .imagens-giratorias-2 img');
3rd solution
var div = document.querySelector('[class^=imagens-giratorias]');
var imagens = document.querySelectorAll('[class^=imagens-giratorias] img');
4th solution
const contador = 1;
const div = document.querySelector('.imagens-giratorias');
const imagens = document.querySelectorAll('.imagens-giratorias img');
I also tried to use from multiple selectors with document.querySelectorAll. No luck.
But all these solutions did not work.
JSFiddle
Please pay attention to two elements. While one element will always animate, another will stop of animating.
https://jsfiddle.net/gusbemacbe/mbp84u6r/2/
If I understand you correctly you're trying to grab elements that have a class name starting with imagens-giratorias. If that's the case, use the ^ attribute selector as shown below:
document.querySelectorAll("[class^="imagens-giratorias"]")
Update:
Based on your update it appears that only one of your two divs' images is animating but in reality they're stacked on top of each of other. Feel free to use whatever layout method you want but for demonstration's sake I floated one left and the other right. Other that it was a matter of looping through your divs and assigning your function to their child images as so:
var divs = document.querySelectorAll('.imagens-giratórias');
var contador = 1;
var mostrarPróximo = function(div) {
contador++;
if (contador > 3) contador = 1;
div.classList.remove('imagem1', 'imagem2', 'imagem3')
div.classList.add('imagem' + contador);
};
Array.from(divs).forEach(function(div, index) {
var images = div.querySelectorAll('img');
Array.from(images).forEach(function(img) {
img.addEventListener('animationend', mostrarPróximo.bind(null, div));
});
});
https://jsfiddle.net/1r6yjf5s/
I want to create a function which manipulates an element with a specific class.
So far I have this:
function myFunc() {
var ball = document.getElementsByClassName('ball');
var myBall = 0;
myBall = ball[0].innerHTML; // HERE I NEED TO GET THE CURRENT BALL CLICKED
myBall[0].innerHTML = ++nr; // THE SAME HERE
}
The problem is that I don't know how to get the exactly div with the class:ball which was clicked. I know that myBall[0] is wrong. I need to set somehow the number representing the element clicked.
My HTML:
<div id="container">
<div class="ball" onclick="myFunc()">1</div>
<div class="ball" onclick="myFunc()">1</div>
<div class="ball" onclick="myFunc()">1</div>
</div>
Something like this
var elems = document.querySelectorAll('#container .ball');
for (var i=elems.length; i--;) {
elems[i].addEventListener('click', myFunc, false);
}
function myFunc() {
this.innerHTML = parseInt(this.innerHTML, 10) + 1;
}
<div id="container">
<div class="ball">1</div>
<div class="ball">2</div>
<div class="ball">3</div>
</div>
From a set of divs I want to select all the divs that contain a specific attribute and then select all the divs that do not contain any of the attributes.
Example:
<div data-attr="1"></div>
<div data-attr="2"></div>
<div data-attr="3"></div>
<div data-attr="4"></div>
<div data-attr="5"></div>
var attrList = [3,4];
// I want to process every div containing attr 3 and 4
attrList.forEach(function(item){
var div = $("[data-attr='"+item+"']");
div.operation_here()
});
// but I also want to process the remaining divs that do not contain neither attr 3 and 4
/* HELP ME HERE - this would select divs with attr 1, 2 and 5 */
How to achieve this?
Make it steps by steps. First, select all div:
var $div = $('div[data-attr]');
Then, select those you need:
var $valid_div = $div.filter(function(){
return attrList.indexOf($(this).data('attr')) > -1;
});
Now you can do your operation on matching div with your variable:
$valid_div.operation_here();
To select remaining div, you can use .not():
var $invalid_div = $div.not($valid_div);
$invalid_div.operation_here();
var $divs = $('div').filter(function() {
// returns all divs with data-attr not equal 1 or 2 or 5
return [1, 2, 5].indexOf(this.data('attr')) == -1;
});
HTML:
<div data-attr="2">not matched</div>
<div data-attr="5">not matched</div>
<div data-attr="6">matched</div>
Given a list of elements, you can use jQuery.not to exclude those elements from another selector
$(function(){
// I want to process every div containing attr 3 and 4
var divs = $('div[data-attr="3"], div[data-attr="4"]');
console.log(divs); // logs 2
var notDivs = $('div[data-attr]').not(divs);
console.log(notDivs); // logs the other 3
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-attr="1"></div>
<div data-attr="2"></div>
<div data-attr="3"></div>
<div data-attr="4"></div>
<div data-attr="5"></div>
I have the following HTML:
<div class="Wrapper">
<div class="SomeOtherClass"></div>
<div class="SomeOtherClass"></div>
<div class="MyClass">
<div class="SomeElement" id="test"></div>
<div class="SomeElement"></div>
</div>
<div class="MyClass">
<div class="SomeElement" id="test2"></div>
<div class="SomeElement"></div>
</div>
</div>
And I have the following javascript:
$('.Wrapper').find('.SomeElement').each(function () {
if (SomeCondition) {
var TheElement = $(this);
var TheIndexOfParentClass = TheElement... //HERE
return;
}
});
As you can see, I loop through all the SomeElements and I pick one. Now I want to know the index of the parent's class (here "MyClass"). For instance, if I pick out "test" then the TheIndexOfParentClass should be 0 and if I pick out test2 then TheIndexOfParentClass should be 1. Note that the number of elements of SomeOtherClass can vary; I don't want the actual index of the parent, I want the index of the parent's class relative to all children of the Wrapper element. How do I do this?
Thanks.
I think you want this :
$('.Wrapper').find('.MyClass').each(function(TheIndexOfParentClass) {
$('.SomeElement', this).each(function(){
if (SomeCondition) {
var TheElement = $(this);
each pass to the callback the iteration index and so by decomposing the iteration you can ask jQuery to count for you.
If you want to stick with your flow, You could do this also by passing class to index method,
$('.Wrapper').find('.SomeElement').each(function () {
if (SomeCondition) {
var TheElement = $(this);
var TheIndexOfParentClass = TheElement.parent().index('.MyClass'); //HERE
return;
}
});
What we are avoiding here is double each loop.
I'm working on a client's HTML based site and need to randomly order a set of Divs on refresh of a page. I would normally handle this through PHP and a database call, but it's a static site.
So, I'm wondering if anyone knows how to randomly display a set of div's using jquery?
Here's an example:
<div class="myItems">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
</div>
and on refresh, it might change to:
<div class="myItems">
<div class="item">2</div>
<div class="item">3</div>
<div class="item">1</div>
</div>
Anyone know how to do that?
This willl do it
function reorder() {
var grp = $(".myItems").children();
var cnt = grp.length;
var temp,x;
for (var i = 0; i < cnt; i++) {
temp = grp[i];
x = Math.floor(Math.random() * cnt);
grp[i] = grp[x];
grp[x] = temp;
}
$(grp).remove();
$(".myItems").append($(grp));
}
Actually it's pretty simple:
$(".myItems").html($(".myItems .item").sort(function(){
return Math.random()-0.5;
}));
That's it!
Enjoy.
Another simple way is ...
1. create an array
2. generate a random number and check if it is Odd or Even
3. If odd, add your div to the top (shift method). If even, add your div to the bottom (push method).
4. So this way you will have your divs arranged randomly in the array.
5. Now simple join the array and append it to your Page.
var divArray = [];
for(var i=0; i<divs.length; i++){
//generate random number
if(rand_num == odd)
divArray.push( div[i] );
else
divArray.shift( div[i] );
}
$(myElem).html( divArray.join("") );