I am writing a function where I want to remove an active class from all elements and add it to the one which was just clicked. Problem is that when I click the element all of them get the active class. Please see the code below.
var pagination = $('.pagination div');
function pager() {
pagination.removeClass('active', function(){
$(this).addClass('active');
});
}
$('.pagination div').on("click", function (){
pager();
});
I could use the code below, which works actually, but the reason I want to use the above one is to have possibility adding other functions in it which will be called later on click.
$('.pagination div').on('click',function(){
$('.pagination div').removeClass('active');
$(this).addClass('active');
});
HTML if needed
<div class="pagination">
<div class="pagination1"></div>
<div class="pagination2"></div>
<div class="pagination3"></div>
<div class="pagination4"></div>
</div>
By using a separate function, you are losing your reference to the current object (this). You will need to use a parameter to get your way working.
function pager(element) {
pagination.removeClass('active', function(){
element.addClass('active');
});
}
$('.pagination div').on("click", function (){
pager($(this));
});
I want to use the above one is to have possibility adding other
functions in it which will be called later
Try this:
function pager(el) {
pagination.removeClass('active', function(){
$(el).addClass('active');
});
}
$('.pagination div').on("click", function (){
pager(this);
});
$('div.pagination').on('click', 'div', function(){
$(this).addClass('active').siblings().removeClass('active');
});
How about this:
var pagination = $('.pagination div');
function pager(selector) {
$('.pagination div').removeClass('active');
$(selector).addClass('active');
}
$('.pagination div').on("click", function (){
pager(this);
});
var pagination = $('.pagination div');
function pager(that) {
pagination.removeClass('active', function(){
that.addClass('active');
});
}
$('.pagination div').on("click", function (){
pager($(this));
});
Editable JSFiddle
HTML
<div class="pagination">
<div class="pagination1">Pagination 1</div>
<div class="pagination2">Pagination 2</div>
<div class="pagination3">Pagination 3</div>
<div class="pagination4">Pagination 4</div>
JavaScript
$(function() { // DOM loaded event handler
function pager (element) {
$(".pagination div").removeClass("active");
element.addClass("active");
}
$(".pagination div").click(function() {
var element = $(this);
pager(element);
});
});
CSS
.active {
color : red;
}
I used your function in 2 steps :
First, I remove all active class by using $(".pagination div").removeClass("active"); which actually apply this effect on all sub div
then, I use the element passed through parameter to the function to scope it, and be able to add the proper class
Use id for all the element then add active class to each element which has been click or use e.target this will track the current element
$('.pagination').click(function(e){
$('.pagination').removeClass('active');
$(e.target).addClass('active');
});
Related
adding active class to parent list when link is clicked/active , am trying to inject that using JavaScript as follow:
$(document).ready(
function()
{
//injecting active status to the navigation bar lists
var element = document.getElementById("navbar-ul");
var links = element.getElementsByTagName("a");
for(var i = 0; i < links.length ; i++) {
links[i].onclick(function () {
links[i].parent().addClass('active');
});
}
}
);
but am getting the following error:
TypeError: links[i].onclick is not a function
how I supposed to achieve that?
A more verbose JQuery way to approach this
$('#navbar-ul a').each(function() {
$(this).on('click', function() {
$(this).parent().addClass('active');
});
});
This is very simply with jQuery:
$("#navbar-ul a").click(function(){
$(this).parent().addClass("active");
});
EXAMPLE 1
I'm guessing you're trying to add an active state to the link thats being clicked on and remove the others? If so you can use .siblings() to find the other links and remove their class:
$("#navbar-ul a").click(function(){
$(this).closest("li").addClass("active").siblings("li").removeClass("active");
});
EXAMPLE 2
You would be better of with adding a class to the tags who needs an eventListener. (with jquery)
$(document).ready(function() {
$("#navbar-ul a").on("click", function() {
var active = document.querySelector('#navbar-ul .active');
if(active){
$("#navbar-ul a").removeClass('active');
}
$(this).addClass("active");
});
);
This question already has answers here:
Events triggered by dynamically generated element are not captured by event handler
(5 answers)
Closed 8 years ago.
doing a accordion, structure is as follows, few divs are coming dynamically, not working.
parent div
<div id="resultarea" class="accordion">
</div>
Inside the parent tag the following tags are coming dynamically.
<div class="accordion-item">
Item 1
<div class="type"></div>
</div>
<div class="data">
my data related to item 1
</div>
<div class="accordion-item">
Item 2
<div class="type"></div>
</div>
<div class="data">
my data related to item 2
</div>
Below is the javascript
$(function($) {
var allAccordions = $('.accordion div.data');
var allAccordionItems = $('.accordion .accordion-item');
$('.accordion > .accordion-item').click(function() {
if($(this).hasClass('open'))
{
$(this).removeClass('open');
$(this).next().slideUp("slow");
}
else
{
allAccordions.slideUp("slow");
allAccordionItems.removeClass('open');
$(this).addClass('open');
$(this).next().slideDown("slow");
return false;
}
});
});
but its not working when the items data is coming dynamically, if static page it is working. please help me to solve this
static one is in jsfiddle find below
http://jsfiddle.net/ea6xX/
Try to use event-delegation on dynamically created elements,
$('.accordion').on('click','.accordion > .accordion-item',function() {
Full code:
$('.accordion').on('click','.accordion > .accordion-item',function() {
if($(this).hasClass('open'))
{
$(this).removeClass('open');
$(this).next().slideUp("slow");
}
else
{
allAccordions.slideUp("slow");
allAccordionItems.removeClass('open');
$(this).addClass('open');
$(this).next().slideDown("slow");
return false;
}
});
Use event delegation - .on() : it binds events to object existing or those which will be added later.
$(document).on('click','.accordion > .accordion-item',function() {
if($(this).hasClass('open'))
{
$(this).removeClass('open');
$(this).next().slideUp("slow");
}
else
{
allAccordions.slideUp("slow");
allAccordionItems.removeClass('open');
$(this).addClass('open');
$(this).next().slideDown("slow");
return false;
}
});
- You need to include jQuery reference in your fiddle.
Because the elements are being appended to the page after DOMReady has fired you need to use a delegated event handler using on(). Try this:
$('#resultarea').on('click', '> .accordion-item', function() {
var allAccordions = $('.accordion div.data');
var allAccordionItems = $('.accordion .accordion-item');
if ($(this).hasClass('open')) {
// your code...
}
});
Note that your variable declarations must go inside the click handler, as on page load the items being selected will not exist.
$(document).on('click', '.accordion .accordion-item', function(e) {
if($(this).hasClass('open'))
{
$(this).removeClass('open');
$(this).next().slideUp("slow");
}
else
{
allAccordions.slideUp("slow");
allAccordionItems.removeClass('open');
$(this).addClass('open');
$(this).next().slideDown("slow");
return false;
}
});
Demo:
http://jsfiddle.net/ea6xX/4/
Use .on as this binds event handler to the selected elements.
For more information click here.
$(function($) {
var allAccordions = $('.accordion div.data');
var allAccordionItems = $('.accordion .accordion-item');
$('.accordion').on("click",".accordion-item",function() {
if($(this).hasClass('open'))
{
$(this).removeClass('open');
$(this).next().slideUp("slow");
}
else
{
allAccordions.slideUp("slow");
allAccordionItems.removeClass('open');
$(this).addClass('open');
$(this).next().slideDown("slow");
return false;
}
});
});
Working JSFiddle
First of all you have to include jQuery in your jsFiddle example. As for dynamic data, you could try to use jQuery on for click event binding.
$('.accordion > .accordion-item').on('click', function() {
...
});
Fixed jsFiddle example
I have this script that I need to run a tab (jquery). Mainly I need to hide some div and add class (you sure have understood).
How should it be written in a more elegant and readable?
function fun1(){
$('#tab1 a').addClass('selected');
$('#tab2 a').removeClass('selected');
$('#tab3 a').removeClass('selected');
document.getElementById('div1').style.display='block';
document.getElementById('div2').style.display='none';
document.getElementById('div3').style.display='none';
}
function fun2(){
$('#tab1 a').removeClass('selected');
$('#tab2 a').addClass('selected');
$('#tab3 a').removeClass('selected');
document.getElementById('div1').style.display='none';
document.getElementById('div2').style.display='block';
document.getElementById('div3').style.display='none';
}
function fun3(){
$('#tab1 a').removeClass('selected');
$('#tab2 a').removeClass('selected');
$('#tab3 a').addClass('selected');
document.getElementById('div1').style.display='none';
document.getElementById('div2').style.display='none';
document.getElementById('div3').style.display='block';
}
window.onload = function() {
document.getElementById('tab1').onclick=fun1;
document.getElementById('tab2').onclick=fun2;
document.getElementById('tab3').onclick=fun3;
document.getElementById('div1').style.display='block';
document.getElementById('div2').style.display='none';
document.getElementById('div3').style.display='none';
}
You should avoid repeating your code. How about a single function that will take care of everything:
function tab(id){
$('#tab1').parent().children().removeClass('selected'); // remove selected class from all tabs
$('#tab' + id).addClass('selected'); // add just to one we need
$('#div1').parent().children().hide(); // hide all the #div elements
$('#div' + id).show(); // show the one we need
}
Notes for the changes I made:
selected class is now applied to #tab elements, not the anchors inside them
I assumed all the #tabs and #divs are the only siblings within their containers
to change the active tab, just call tab(1), tab(2), etc...
Here's a simple example with my approach: http://jsfiddle.net/CkpwT/1/
You could try something like this:
var tabs, divs;
function handler(n) {
return function fun() {
for(var i=0, l=tabs.length; i<l; ++i)
tabs[i].find('a').toggleClass('selected', n==i);
for(var i=0, l=divs.length; i<l; ++i)
divs[i].toggle(n==i);
};
}
window.onload = function() {
tabs = [$('#tab1'), $('#tab2'), $('#tab3')];
divs = [$('#div1'), $('#div2'), $('#div3')];
for(var i=0, l=tabs.length; i<l; ++i)
tabs[i].on('click', handler(i));
tabs[0].click();
}
Demo
So, you have a tab for every page. And on click you want to also add a 'selected' class to the clicked element.
PLAYGROUND
All you need is basically this simple HTML markup:
<ul id="tabs">
<li>Tab1</li>
<li>Tab2</li>
<li>Tab3</li>
</ul>
<div id="divs">
<div>Div1</div>
<div>Div2</div>
<div>Div3</div>
</div>
than you can simply get the index value of the clicked tab and open the same indexed DIV element:
$tabs = $('#tabs a'); // Cache your selectors
$divs = $('#divs > div');
$tabs.click(function(e) {
e.preventDefault(); // prevent browser from following anchor href
$tabs.removeClass('active');
$(this).addClass('active');
$divs.hide().eq( $tabs.index(this) ).show(); // Get the Tab element index and refer to the DIV using .eq()
}).eq(0).click(); // Trigger the initial click on a desired tab index(0)
Im trying to grab the "title" on the <li> when it is clicked. It keeps returning undefined.
html
<div id="sidebar">
<div class="navigation">
<ul>
<li title="../../000_Movies/_assets/playlist.html">فیلم ها</li>
</ul>
</div>
</div>
js
$('.navigation li').click(function () {
$('.slider').animate({
marginLeft: 0
}, 500,function() {
var test = $(this).attr('title');
alert(test);
location.href = '';
});
});
This doesn't work?
$('li').click(function(){
alert($(this).attr('title'));
});
"this" maybe is not the li. Or the browser have a bug (IE?). Your code seems correct to me.
You should create a closure on the clicked li element. You're getting this inside another function in the click handler function, so the definition of this will be different than the original function.
$('.navigation li').click(function () {
// cache the element here
var that = $(this);
$('.slider').animate({
marginLeft: 0
}, 500, function() {
// then access that instead here
// (we're creating a closure on the that variable)
var test = that.attr('title');
alert(test);
location.href = '';
});
});
If you have two nested functions, their this variables will be different:
function foo () {
// this here ...
function bar () {
// ... is different from this here
}
}
So building on that...
$('li').click(function () {
// $(this) here ...
$('something').slider({},100, function () {
// ... is different from $(this) here
});
});
$("li").on('click',function () {alert($(this).attr('title');)});
How are you attaching the click handler on the li element? Are you sure this inside the handler is poiting to li element.
I would try to log this and find out what it points to.
If this points to li then $(this).attr('title') should work perfectly fine.
I'm guessing it would be:
$("li.clickMe").click(function () {
$("this").attr("title").whateverYouNeedToDo("");
});
My code (the html page):
<nav>
<ul>
<li id="homeLink">Home</li>
<li id="rekenLink">Rekenmachine</li>
<li id="bakkerLink">Parkeergarage</li>
<li id="garageLink">Bij de bakker</li>
<ul>
</nav>
The javascript/jquery behind it:
$(function () {
$("ul").click(function () {
// here I want to get the clicked id of the li (e.g. bakkerLink)
});
});
How do I do that?
Use the .on() method with signature $(common_parent).on(event_name, filter_selector, event_listener).
Demo: http://jsfiddle.net/gLhbA/
$(function() {
$("ul").on("click", "li", function() {
// here I want to get the clicked id of the li (e.g. bakkerLink)
var id = this.id;
alert(id);
});
});
Another method is to bind the event to li instead of ul:
$(function() {
$("li").click(function() {
// here I want to get the clicked id of the li (e.g. bakkerLink)
var id = this.id;
alert(id);
});
});
Use jQuery on() instead of click and pass li as selector.
$(function() {
$("ul").on('click', 'li', function() {
//Here this will point to the li element being clicked
alert(this.id);
});
});
on() reference - http://api.jquery.com/on/
$(function() {
$("li").click(function() {
alert(this.id);
});
});
edit: jsfiddle link
Handle the click event of the <li> instead of the <ul>.
You can then get this.id.
Use the event's target (The anchor that was clicked) and then grab its parent's id:
$(function() {
$("ul").click(function(e) {
alert(e.target.parentNode.id);
});
});
JSFiddle
here is one of the way to do. Make sure your using the latest jquery file.
$("ul li").on('click', function() {
console.log($(this).attr("id"));
});
You may try
$(function () {
$("li").click(function () {
var id = $(this).attr("id");
alert(id);
});
});
or
$(document).ready( function() {
$("li").click(function () {
var id = $(this).attr("id");
alert(id);
});
});