problems getting element position in array - javascript

UPDATED WITH THE CORRECT FIDDLE LINK
I have the following example: http://jsfiddle.net/gespinha/kRUym/52/
Every time you click an element of the array it logs to the console its position in the array and the position of the next element. What I'm trying to do is that when I click on the last element I want it to identify that the next element is actually the first (looping the array).
But when when I click on the last element it doesn't set the arrayPos variable (the number of the position in the array: articles) to zero (the first position in the array, it just continues to number 6, even though I have stated in the if argument that if it is bigger than the length of the array it should become zero.
Why is this happening?
Any suggestions?
HTML
<div class="item">index 0</div>
<div class="item">index 1</div>
<div class="item">index 2</div>
<div class="item">index 3</div>
<div class="item">index 4</div>
<div class="item">index 5</div>
JQUERY
var articles = [];
$('.item').each(function(){
var obj = $(this);
articles.push(obj);
});
for (var i = 0; i < articles.length; i++) {
$(articles[i]).data("index", i)
}
$('.item').on("click", function() {
var id = $(this).data("index");
console.log('NOW: '+id);
if(id < articles.length){
id++
} else {
id = 0;
}
console.log('NEXT: '+id);
});
How can I make this work?

I believe it's a 1 off issue...try
if (id < articles.length - 1)

You can simply use the jQuery index():
$('.item').click(function(){
alert( $(this).index() );
});
This will alert the index starting from 0.
This requires the items to be in a seperate div, the index is the index relative to the parent.

LIVE DEMO
$(function(){
var articles = [];
$('article').each(function(){
articles.push( this );
});
$(articles).click(function(){
console.log( $(this).index() );
});
});
Note that this way you'll just collect the indexable articles (every children will always be index 0). You can push the JS this element into a collection of elements and than on click reference their original index value by wrapping the JS elements into a jQuery Object Elements collection $(articles).

Related

Target by ID elements in array assigned by get() jQuery

Apologies if I get the terminology wrong here.
I have a 'grid' of images in html that I want to use jQuery to fade in each element randomly. One item in the grid is a Logo - I want it to fade in last. The grid size could be changed and the position of the 'logo' could also be different. Here is a reduced simplified output of the list.
<ul id="homepage-grid" class="projectsgrid row">
<div id="item1">
</div>
<div id="item2">
</div>
<div id="itemlogo" style="opacity: 0;">
<a href="#" class="block" style="padding-bottom: 100%;">
<div style="background-image:url('logoonly.png')" title="" class="logoblock"></div>
</a>
</div>
<div id="item4">
</div>
<div id="item5">
</div>
</ul>
I have the following script which will collect the elements into an array.
But i can't figure out how to match the element with the 'itemlogo' ID in the collection to split it out and push it to the end of the array so it is last to 'fade in'. I have tried "div#itemlogo", "#itemlogo", "itemlogo" but nothing seems to match, and perhaps not knowing the name of what I am doing I can't find any references.
var elems = $('#homepage-grid > div').get(); // collect elements
console.log(elems);
for (var i = elems.length - 1; i > 1; i--) { // Shuffle the order
var j = Math.floor(Math.random() * (i + 1));
var elem = elems[j];
elems[j] = elems[i];
elems[i] = elem;
}
elms = elems.push(elems.splice(elems.indexOf('div#itemlogo'), 1)[0]); // pull logo to last??
var i = 0;
var timer = setInterval(function() { // animate fade them sequentially
console.log(elems[i]).id();
$(elems[i]).fadeTo( "slow" , 1);
if (i === elems.length) {
clearInterval(timer);
}
i++;
}, 150);
You're on the right path, but the key here is that you need to find a particular item. Those items are DOM elements, not strings or selectors on their own.
elems.push(
elems.splice(
elems.findIndex(node=>node.id === 'itemlogo'),
1
)[0]
);
findIndex allows you to pass a function that should return true for the item you want - in this case, you want the item whose ID is itemlogo. The rest is just the same push-splice thing you have already.
I would also like to praise your correct use of array shuffling. You can simplify it a little bit with destructuring:
[elems[i], elems[j]] = [elems[j], elems[i]];

How can I count how many divs whose ids begin with a certain text that are inside a div using JQuery?

Here's the html:
<div class="col-sm-12" id="ProdutosPedido">
<div class="row">
<div class="col-sm-12 formProdutoAdd" id="produto_1">
...
</div>
</div>
</div>
As things happen within the page, divs are appended inside #ProdutosPedido, and #produto_1 increments to #produto_2 and so on.
This is not working for me:
console.log($("#ProdutosPedido > [id^=produto_]").length);
I need to iterate over these "produto_" and use the 'i' to refer to the current div, but I don't know how to do it. My example logs 0, and that should not be the case, since it starts with 1.
Since your produto divs are not direct children of ProdutosPedido, but its descendants, you need to use the following selector:
$("#ProdutosPedido [id^=produto_]")
Here is the working JSFiddle demo.
Pure Javascript Solution
function CountDiv() {
var nodes = document.getElementById('ProdutosPedido').getElementsByTagName('*');
var Count = 0;
for (var i = 0; i < nodes.length; i++) {
if (nodes[i].id.substring(0, 8) == 'produto_')
Count++;
}
alert(Count);
}

Remove subsequent duplicate elements by class

Via javascript or jquery, I am in need of removing duplicate elements in sets so that one remains. They're all the same, so it doesn't matter which are removed so long as one remains. The page appears as follows:
<div class="column-hr"></div>
<div class="column-hr"></div>
<div class="column-dude"></div>
<div class="column-hr"></div>
<div class="column-hr"></div>
<div class="column-dude"></div>
<div class="column-hr"></div>
One <div class="column-hr"></div> before every <div class="column-dude"></div> needs to stay, but every subsequent hr column before every dude column needs to go.
I tried the following, hoping it would be this simple. Didn't work.
$( "div.column-hr" ).each(function( index ) {
if ($(this).next('div.column.hr')) {
$(this).remove();
}
});
You can achieve this with sibling selector +. Very easy and also the fastest solution, since the browser's CSS engine will be used to select elements:
$(".column-hr + .column-hr").remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="column-hr">hr</div>
<div class="column-hr">hr</div>
<div class="column-dude">dude</div>
<div class="column-hr">hr</div>
<div class="column-hr">hr</div>
<div class="column-dude">dude</div>
<div class="column-hr">hr</div>
How it works: CSS selector .column-hr + .column-hr selects .column-hr elements that have immediate previous sibling .column-hr. As the result this expression will select all adjacent .column-hr elements except the very first one, because the first one doesn't have another .column-hr right before it.
You can try this:
$( ".column-hr" ).each(function() {
console.log($(this).html());
console.log($(this).next().attr('class'));
if ($(this).next().attr('class') == 'column-hr') {
$(this).remove();
}
});
https://jsfiddle.net/aodnw5ns/
var classesToRemove = ['column-hr', 'column-dude'];
var $elements;
for (var i = 0, l = classesToRemove.length; i < l; i++) {
// Find elements
$elements = $('.' + classesToRemove[i]);
var elementsLength = $elements.length;
// If there is more than one element
if (elementsLength > 1) {
// get all elements except the first
$elements = $elements.slice(1, elementsLength);
// remove them
$elements.remove();
}
}
// prevent memory leaks
$elements = null;
JSFiddle

swap 2 div's index using pure javascript

I have a parent div and it has 9 same div's am trying to swap two div's index. Following is my code:
HTML:
<div id="cont" class="container">
<div class="no">1</div>
<div class="no">2</div>
<div class="no">3</div>
<div class="blank"></div>
<div class="no">4</div>
<div class="no">5</div>
<div class="no">6</div>
<div class="no">7</div>
<div class="no">8</div>
</div>
now I want to swap say 5th and 6th indexed elements. I have no clue how to do that in JavaScript. I know there is function called .index() but how to do that in pure JS.
Here's one implementation: http://jsfiddle.net/x8hWj/2/
function swap(idx1, idx2) {
var container = document.getElementById('cont');
// ditch text nodes and the like
var children = Array.prototype.filter.call(
container.childNodes,
function(node) {
return node.nodeType === 1;
}
);
// get references to the relevant children
var el1 = children[idx1];
var el2 = children[idx2];
var el2next = children[idx2 + 1];
// put the second element before the first
container.insertBefore(el2, el1);
// now put the first element where the second used to be
if (el2next) container.insertBefore(el1, el2next);
else container.appendChild(el1);
}
This starts by getting a list of all element child nodes, then uses insertBefore to rearrange them.

Calculate the number of html element with js

I have multiple div elements with same id='mydiv'.I want to calculate these divs and Iam using the code
document.getElementById('mydiv').length
But it is not working
What you should do is use class instead of ID's. ID is for one element only, class is for multiple.
http://jsfiddle.net/d7AHV/
It won't work as getElementById will always return an element with the specified ID and null if the specified ID doesn't exist
From ECMA
getElementById(elementId) This method returns a Element. The elementId
parameter is of type DOMString.
What you can do is to assign each div with class
<div class="mydiv"></div>
<div class="mydiv"></div>
<div class="mydiv"></div>
<div class="mydiv"></div>
<div class="mydiv"></div>​​​​​​​​​
And iterate over:
var divs = document.getElementsByTagName('div');
var count = 0;
for(var i = 0; i < divs.length; i++) {
if(divs[i].className == 'mydiv') count++;
}
alert(count);
If your clients support document.getElementsByClassName(), it's even more concise:
alert(document.getElementsByClassName('mydiv').length)
You've been told about multiple elements with the same ID, but in rare cases it might be unavoidable (e.g. an XML document over which you have no control). The only adverse behaviour is that selecting by ID will usually only return the first one (but that's not guaranteed).
You can count elements with the same id by looping over all the elements in the document and counting the ones with a matching id, e.g.
function countSameIds(id) {
var allNodes = document.getElementsByTagName('*');
for (var i=allNodes.length, count=0; i; ) {
if (allNodes[--i].id == id) {
++count;
}
}
return count;
}

Categories