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>
Related
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
I have a javascript code that retrieves an id from a CollectionType Symfony:
$(document).ready(function() {
$('.well').change(function () {
var day_n = document.getElementById('command_billet_billet_0_dateBirthday_day').value;
var month_n =
document.getElementById('command_billet_billet_0_dateBirthday_month').value;
var year_n =
document.getElementById('command_billet_billet_0_dateBirthday_year').value;
Each time a new form is added, this id will become
document.getElementById('command_billet_billet_1_dateBirthday_day').value;
document.getElementById('command_billet_billet_1_dateBirthday_month').value;
document.getElementById('command_billet_billet_1_dateBirthday_year').value;
document.getElementById('command_billet_billet_2_dateBirthday_day').value;
document.getElementById('command_billet_billet_2_dateBirthday_month').value;
document.getElementById('command_billet_billet_2_dateBirthday_year').value;
the number changes and the end of id (day, month, year)
Is it possible to integrate javascript code inside getElementById to get all the numbers and make the distinction of the end of id ?
document.querySelectorAll() could do it.
var ps = document.querySelectorAll('[id^=id]');
console.log(ps);
for(i in ps){
ps[i].style.color = 'red';
}
<p id="id1A">Hello</p>
<p id="id2A">World</p>
<p id="id3A">Hello!</p>
Logic
Fetch all elements using generic selector
Loop over them and get ID
Now use a regex or any other string manipulator to get number.
Sample
(function(){
var digitReg = /\d+/;
var wells = document.querySelectorAll('.well');
for(var i = 0; i< wells.length; i++){
var id = wells[i].getAttribute('id');
console.log(id.match(digitReg)[0])
}
})()
<div class="well" id="command_billet_billet_1_dateBirthday_day"></div>
<div class="well" id="command_billet_billet_2_dateBirthday_day"></div>
If you can change your html markup then you can use jQuery data() api
Like this :
$(function() {
$("#getIds").click(function() {
var ids = [];
$(".well").each(function() {
ids.push($(this).data("id"));
})
console.log(ids);
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="well" data-id="1"> div Id 1</div>
<div class="well" data-id="2"> div Id 2</div>
<div class="well" data-id="3">div Id 3</div>
<div class="well" data-id="4"> div Id 4</div>
<div class="well" data-id="5">div Id 5</div>
<div class="well" data-id="6">div Id 6</div>
<button id="getIds" type="button">Get Ids</button>
I want to traverse through pages and toggle active class through them. How should I do this without using set class?
HTML
<div class="page active"></div>
<div class="set">
<div class="page"></div>
<div class="page"></div>
</div>
<div class="page"></div>
jQuery
$('.active').toggleClass('active').toggle().nextAll('.page').toggleClass('active');
I am assuming that by "traverse" you mean you want to toggle the .page divs one by one in a certain order.
If that is the case, write an algorithm that traverses a tree: given a root, toggle if it is a .page, and recursively deal with each of its children
function traverse(root){
if(!root) return;
if(root.hasClass('page')) root.toggle('active');
root.children().forEach(function(child){
traverse(child);
});
//lets say you want to bind to click event on every div
$('div').click(function(){
traverse($(this));
});
}
Unfortunately we don't have a direct way to find the next non sibling element, but we can handle that situation in many ways using jquery functions. I just tried on way to achieve your goal, check out this working fiddle and let me know if you need any clarity, added some inline comments also for your understanding.
HTML:
<div class="page active">div 1</div>
<div class="page">div 2</div>
<div class="set">
<div class="page">set 1 - div 1</div>
<div class="page">set 1 - div 2</div>
<div class="page">set 1 - div 3</div>
</div>
<div class="page">div 5</div>
<div class="set">
<div class="page">set 2 - div 1</div>
<div class="page">set 2 - div 2</div>
</div>
<div class="page">div 6</div>
<button class="next-btn">Next</button>
CSS:
.active {
color: red;
}
.next-btn {
cursor: pointer;
}
Javascript:
$(function() {
$('button').click(function() {
var elem = $(".page.active").toggleClass('active'); // current active element
var nextElem = elem.next(); // next element
// go above one level and get next element
// if no next element exists, means end of the child level
if (!nextElem.length) {
nextElem = elem.parent().next();
}
// if next element has some PAGE children then update the first child element
if (nextElem.children('.page').length > 0 ) {
nextElem.children('.page:first-child').toggleClass('active');
} else if (nextElem.hasClass('page')) {
nextElem.toggleClass('active');
}
});
});
This approach handles the scenario with one child level, you can extend this to multiple levels also with recursive functions, I think this helps you to handle your scenario accordingly.
Working fiddle
You could achieve that using indexes to get the next element in the DOM using the index of active one +1 then active it, I think the following is what you are looking for:
var getActiveIndex = function(){
var active_index;
$('.page').each(function(i){
if ( $(this).hasClass('active') )
active_index = i;
})
return active_index;
}
$('body').on('click', '.next', function(){
var active_page_index = getActiveIndex(); //Get active page index
var new_index = active_page_index+1; //Set the next page index
var next_page = $('.page:eq('+new_index+')'); //Get the next page
$('.page').removeClass('active');
if(next_page.length)
next_page.addClass('active');
else
$('.page:first').addClass('active');
})
I hope this helps.
var getActiveIndex = function(){
var active_index;
$('.page').each(function(i){
if ( $(this).hasClass('active') )
active_index = i;
})
return active_index;
}
$('body').on('click', '.next', function(){
var active_page_index=getActiveIndex();
var new_index = active_page_index+1;
var next_page = $('.page:eq('+new_index+')');
$('.page').removeClass('active');
if(next_page.length)
next_page.addClass('active');
else
$('.page:first').addClass('active');
})
.active{
background-color: red;
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="page active">page</div>
<div class="set">
<div class="page">- Set page</div>
<div class="page">- Set page</div>
</div>
<div class="page">page</div>
<div class="page">page</div>
<div class="page">page</div>
<div class="set">
<div class="page">- Set page</div>
<div class="page">- Set page</div>
</div>
<div class="page">page</div>
<br>
<button class='next'>Active the next page</button>
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>
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
});