jQuery getting element index despite wrapper / parent element? - javascript

I have divs with same class, but each 3 are wrapped in a parent div. I can't get the index the way I want it. I am sorry, could anyone help me to get the index as number from 0 to 8.. when i click on any element? despite the parent element.
Here is my full code for your testing.
<div class="more-content">
<div class="post">post 1</div>
<div class="post">post 2</div>
<div class="post">post 3</div>
</div>
<div class="more-content">
<div class="post">post 4</div>
<div class="post">post 5</div>
<div class="post">post 6</div>
</div>
<div class="more-content">
<div class="post">post 7</div>
<div class="post">post 8</div>
<div class="post">post 9</div>
</div>
<script type="text/javascript">
$(function() {
// navigate posts with next/prev buttons
$(".post").click(function(){
alert($(this).index());
});
});
</script>
If i click i get index 0, 1, 2 ..i think because each 3 items are wrapped in parent? I am new with jquery, any help appreciated. what i need is get the index of post with same class.. say post 6 = index 5.. and so on
UPDATE
How can I get the same result if the clicked element is a child anchor in the post div and not the post div directly?

Try index method with this as an argument:
$(".post").click(function() {
alert($(".post").index(this));
});​
DEMO: http://jsfiddle.net/Nryf3/

var posts = $('.post').click(function(){
alert(posts.index(this));
});
DEMO: http://jsfiddle.net/paZ2e/

You could loop through all elements tagged post and increment a counter until you find the object you're looking for, like this:
$(".post").click(function() {
var counter = 0;
var that = this;
$(".post").each(function() {
if(that == this) break;
counter++;
}
// counter now equals the index of the post element out of all posts on the page
});

Related

Get first three child elements of parent with jQuery

I want to get the first 3 elements in a div, so e1, e2 and e3:
<div id="parent">
<div id="e1">element 1</div>
<div id="e2">element 2</div>
<div id="e3">element 3</div>
<div id="e4">element 4</div>
</div>
I want to do this with jQuery. What's the best way to achieve this?
Actually you can do this with nth-child pseudo-class with functional notation. So this will work like:
:nth-child(-n+3)
Represents the first three elements. [=-0+3, -1+3, -2+3]
Where the functional notation represents elements in a list whose indices match those found in a custom pattern of numbers, defined by An+B, where:
A is an integer step size,
B is an integer offset,
n is all positive integers, starting from 0.
So your final code would be something like:
const elements = document.querySelectorAll('#parent > div:nth-child(-n+3)')
elements.forEach(element => {
console.log(element.id)
})
<div id="parent">
<div id="e1">element 1</div>
<div id="e2">element 2</div>
<div id="e3">element 3</div>
<div id="e4">element 4</div>
</div>
But if you want to stick with jQuery itself you can use jQuery :lt() instead. Where jQuery( ":lt(index)" ) Select all elements at an index less than index within the matched set
The output will be something like this:
const elements = $('#parent > div:lt(3)')
jQuery.each(elements, function (index, element) {
console.log(element.id)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="parent">
<div id="e1">element 1</div>
<div id="e2">element 2</div>
<div id="e3">element 3</div>
<div id="e4">element 4</div>
</div>
You can use jQuery's .each() function and a little conditional if statement with the function's index...
$('#parent').children().each(function(index){
// To counteract the zero-based index.
index++
if (index < 4) {
console.log(this);
}
});
Example on Codepen

add class every 5 items(div) when i click on button

i need to add class every 5 items(div) when i click on button
Does anybody know how to add class every 5 elements using jQuery's each?
var i = 0;
$(document).ready(function() {
$('a[href=#]').click(function() {
$('.element-item').each(function(i+5) {
});
});
http://jsfiddle.net/SeanWessell/8yuqb5u3/
$('a').click(function() {
$('.element-item:not(.newClass)').each(function(ix) {
$(this).addClass('newClass')
return (ix < 4)
})
})
Returning a false value will exit the each function.
Pass the index to the each function and return ix < 4 since index is 0 based.
Use $.slice to get a range of elements. You can see the documentation here: http://api.jquery.com/slice/
$('.element-item').slice(0,5).addClass('class_name');
I'm not completely clear on the question but provided two possible answers to what I think you're asking for:
$(function() {
$('a[href="#"]').on('click', function() {
// Every 5th element
$('.element-item:nth-child(5n)').addClass('sample');
// First 5 elements
$('.element-item:lt(5)').addClass('sample');
});
});
You can use the first parameter (indexInArray) of the jQuery .each to get the index of the array.
Then you can use the Remainder (%) to add the class for every fifth item.
Maybe this example can get you started:
$(document).ready(function() {
$('a[href=#]').click(function() {
$('.element-item').each(function( index, value ) {
var itemNumber = index + 1;
if (itemNumber % 5 === 0) {
$(value).addClass('newClass');
}
});
return false;
});
});
.newClass {
border: 1px solid #000;
}
.element-item {
padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
link
<div class="element-item">element 1</div>
<div class="element-item">element 2</div>
<div class="element-item">element 3</div>
<div class="element-item">element 4</div>
<div class="element-item">element 5</div>
<div class="element-item">element 6</div>
<div class="element-item">element 7</div>
<div class="element-item">element 8</div>
<div class="element-item">element 9</div>
<div class="element-item">element 10</div>
<div class="element-item">element 11</div>

Create a variable that contains the id of clicked div

Does anybody have any idea how to create a variable that contains the id of a clicked div?
I want to hide all the #content-wrappers on page load apart from the first one then when the .square has been clicked for it to display the div with the same class as the id that has been clicked, it doesn't make much sense when you write id down but if you look at my fiddle then it should hopefully make sense?
http://jsfiddle.net/alexjamest/Lkaxza22/
$('#content-wrapper').hide();
$(".square").click(function() {
var id_name= $(this).attr(id);
if $('#content-wrapper').hasClass(id_name){
$(this).fadeIn();
}
});
<div id="content-wrapper" class="c1">Content 1</div>
<div id="content-wrapper" class="c2">Content 2</div>
<div id="content-wrapper" class="c3">Content 3</div>
<div id="content-wrapper" class="c4">Content 4</div>
<div id="content-wrapper" class="c5">Content 5</div>
<div id="content-wrapper" class="c6">Content 6</div>
<div id="content-wrapper" class="c7">Content 7</div>
<div id="content-wrapper" class="c8">Content 8</div>
<div class="square" id="c1"></div>
<div class="square" id="c2"></div>
<div class="square" id="c3"></div>
<div class="square" id="c4"></div>
<div class="square" id="c5"></div>
<div class="square" id="c6"></div>
<div class="square" id="c7"></div>
<div class="square" id="c8"></div>
Change your content-wrappers elements so that they contain classes, not ids, since ids should be unique. You can, however, identify your content with some sort of a prefix, like content-:
<div class="content-wrapper" id="content-c1">Content 1</div>
<div class="content-wrapper" id="content-c2">Content 2</div>
<div class="content-wrapper" id="content-c3">Content 3</div>
<div class="content-wrapper" id="content-c4">Content 4</div>
<div class="content-wrapper" id="content-c5">Content 5</div>
<div class="content-wrapper" id="content-c6">Content 6</div>
<div class="content-wrapper" id="content-c7">Content 7</div>
<div class="content-wrapper" id="content-c8">Content 8</div>
Then the following code will work:
$(document).ready(function()
{
$(".content-wrapper").hide();
$(document).on("click", ".square", function()
{
var id = $(this).attr("id");
$("#content-"+id).fadeIn();
});
});
Note the following part
$(".content-wrapper").hide();
which is important, since we're identifying that we wish to hide all elements which contain the class content-wrapper, not the id content-wrapper.
Working Demo.
There are four problems with your code:
$('#content-wrapper').hide(); will only hide the first element with that ID, because IDs have to be unique. Use a common class instead.
var id_name= $(this).attr(id);. id is an undefined variable. You probably want to pass the string "id" instead, or better, just access the property of the DOM element: this.id.
if $('#content-wrapper').hasClass(id_name){ is a syntax error. The condition has to be put in parhenthesis:
if ($('#content-wrapper').hasClass(id_name)) {
However, that alone won't make the condition work, since again, #content-wrapper will only select the first element. Just select the corresponding element by class:
$('.' + this.id).fadeIn();
You can also add .content-wrapper for more granular filtering:
$('.content-wrapper.' + this.id).fadeIn();
Fixed code:
$('.content-wrapper').hide(); // give that class to all elements instead of the ID
$(".square").click(function() {
$('.' + this.id).fadeIn();
});
DEMO
A JQuery-less solution, still with the fade animation.
On load it gets an array of buttons and an array of content wrappers, then it just uses the order to figure out which box to reveal. Will only work with an equal number of buttons and wrappers. I started the wrappers as invisible in the style sheet, so we only have to reveal them. Also remembers which buttons was clicked last and resets its visibility.
<head>
<style>
.content-wrapper{
opacity:0;
transition:opacity 1s ease;/* only showing the normal one, prefixed may be required for portability*/
}
</style>
<script>
window.addEventListener('load',onload,false);
var wrappers;
var buttons;
var last;
function onload(){
wrappers = document.getElementsByClassName('content-wrapper');
buttons = document.getElementsByClassName('square');
var i = buttons.length;
while(i--) // add listener for each button
buttons[i].addEventListener('click',onclick,false);
}
function onclick(){
if(last)wrappers[last].style.opacity = '0.0'; //hide previous
var i = buttons.indexOf(this);
wrappers[i].style.opacity = '1.0'; //show clicked
last = i;
}
</script>
</head>
<body>
<div class='content-wrapper'></div>
<div class='content-wrapper'></div>
<div class='content-wrapper'></div>
<div class='content-wrapper'></div>
<div class='content-wrapper'></div>
<div class='square'></div>
<div class='square'></div>
<div class='square'></div>
<div class='square'></div>
<div class='square'></div>
</body>

How can I hide elements after exceeding a certain count JavaScript or jQuery?

I currently have a div with 8 children divs, but only want to display the first four. What's the easiest way to go about this with javascript or jQuery so that even if the children div's change, the last four divs will always be hidden or display: none?
<div class="wrapper">
<div class="tour">Tour 1</div>
<div class="tour">Tour 2</div>
<div class="tour">Tour 3</div>
<div class="tour">Tour 4</div>
<div class="tour">Tour 5</div>
<div class="tour">Tour 6</div>
<div class="tour">Tour 7</div>
<div class="tour">Tour 8</div>
</div>
Using css, nth-child
.wrapper > :nth-child(n + 5) {
display: none;
}
Demo: Fiddle
of jQuery use .slice() since it is faster than the alternate :lt
$('.wrapper > .tour').slice(4).hide()
Demo: Fiddle
Arun P Johny's answer is great, but in case you needed to do this using jQuery:
$('.wrapper .tour:gt(3)').hide();

JavaScript Show/Hide as Filters to list of divs

Looking to create Javascript that acts like a filter on a list of divs.
For instance, here's the intended markup...
Filter Item 1
Filter Item 2
Filter Item 3
Filter Item 4
Filter Item 5
<div class="1">Item 1</div>
<div class="1">Item 1</div>
<div class="2">Item 2</div>
<div class="3">Item 3</div>
<div class="1">Item 1</div>
<div class="4">Item 4</div>
<div class="4">Item 4</div>
<div class="1">Item 1</div>
<div class="5">Item 5</div>
I want to be able to click on the link for Item 1, and show only Item 1 divs and hide all other divs, click the link of Item 2, and show only Item 2 divs and hide all other divs and so on. I've seen several similar scripts but nothing that seemingly turns divs matching the class on/off in this manner.
This can be done easily in Jquery, following should work for you, but you have to modify your html as following
Filter Item 1
Filter Item 2
Filter Item 3
Filter Item 4
Filter Item 5
<div class="1">Item 1</div>
<div class="1">Item 1</div>
<div class="2">Item 2</div>
<div class="3">Item 3</div>
<div class="1">Item 1</div>
<div class="4">Item 4</div>
<div class="4">Item 4</div>
<div class="1">Item 1</div>
<div class="5">Item 5</div>
and javascript as follows
$(document).ready(function(){
$(".link").click(function(e){
$("." + e.currentTarget.id).toggle()
}
});
You can use jQuery's toggle. below is simple example:
$(document).ready(function() {
$('#IDOfLink').click(function() {
$('.class1').toggle("slow");//switch to show/hide when clicked
//hide other div u wish
});
$('#anotherLinkID').click(function() {
$('.class2').toggle("fast");//switch to show/hide when clicked
//hide other div u wish
});
//...etc...
});
Very simple solution:
Filter Item 1
This, ofcourse, will hide all the other div's on page, so you should give the all some other class or put inside another div. Then the code could be:
Filter Item 1
<div id="filtered">
<div class="1"></div>
...
</div>
Set an ID for each link, then assign an onclick event. There you can filter out divs using the clicked link ID.
Something like this (http://jsfiddle.net/pJRek/1/)
Markup:
Filter Item 1
Filter Item 2
Filter Item 3
Filter Item 4
Filter Item 5
<div class="group_1">Item 1</div>
<div class="group_1">Item 1</div>
<div class="group_2">Item 2</div>
<div class="group_3">Item 3</div>
<div class="group_1">Item 1</div>
<div class="group_4">Item 4</div>
<div class="group_4">Item 4</div>
<div class="group_1">Item 1</div>
<div class="group_5">Item 5</div>
And script:
$(document).ready(function(){
var links = $('.bound');
var divs = $('div');
links.click(function(event){
divs.hide();
divs.filter('.' + event.target.id).show();
});
});
If you setup your HTML as:
<div id="controls">
Filter Item 1
Filter Item 2
Filter Item 3
Filter Item 4
Filter Item 5
</div>
<div id="items">
<div class="1">Item 1</div>
<div class="1">Item 1</div>
<div class="2">Item 2</div>
<div class="3">Item 3</div>
<div class="1">Item 1</div>
<div class="4">Item 4</div>
<div class="4">Item 4</div>
<div class="1">Item 1</div>
<div class="5">Item 5</div>
</div>
Then your jQuery code can be as simple as:
$(function(){
$("#controls a").click(function() {
$("#items").find("." + this.id).toggle();
});
});
Of course, you will want to add a visual indication that a filter is toggled on and off.
You may not want to associate the items with each link through id/classes, but instead use jQuery's data storage, depending on your needs.
A working example, tested in firefox, here: http://jsfiddle.net/mwolfetech/GetRV/
Edit: This solution is similar to Anto Binish Kaspar's, mainly differing only in
how the html is modified. I think that the divs given are likely to be a good structure for your document anyway, and eliminates the need for extra classes for control. This is always a design decision--balancing div (for structural division) vs class (for, categories). Additionally, theres no need to extract the id from the event object as jQuery provides the this reference.
Give them all another class (for example item) and then make the click hide all item and show all of the selected value.

Categories