jquery if has class issue - javascript

I am using bootstrap tabs and I wanted to do some functions with javascript if LI is clicked but with conditional, if it's active do nothing, else do this...
I have come up with this code to check if it has a class="active" since bootstrap tabs adds class="active" to LI for the active tab but it doesn't work well, it always returns true, what I am doing wrong here?
code
var i = $( "li" ).hasClass( "active" );
$( "li" ).click(function() {
if (i == true ) {
console.log("the tab is already active");
}
else {
console.log("selected");
}
});
here is jsfiddle demo

Use $(this) for taken current object
$( "li" ).click(function() {
if ($(this).hasClass("active")) {
console.log("the tab is already active");
}
else {
console.log("selected");
}
});
Fiddle

Check hasClass for clicked li:
$( "li" ).click(function() {
if ($(this).hasClass('active') ) {
console.log("the tab is already active");
}
else {
console.log("selected");
}
});

Because $("li") returns all the li tags. And the initial state of the first li tab is active, so the i variable is always true.
Change the codes to what #Bhojendra Sah wrote will work.

You can try this as well for dynamic elements:
$(document).on('click', "li.active", function (e) {
console.log("the tab is already active");
}).on('click', "li:not(.active)", function (e) {
console.log("selected");
});
Example

$( "li" ).click(function() {
if ($(this).hasClass("active") ) {
console.log("the tab is already active");
}
else {
console.log("selected");
}
});

Related

How to add event listener using jQuery?

Have this code and tried to hide my side navbar when clicked outside the #nav, got this error.
Cannot read property 'addEventListener' of null
$( document ).ready( function() {
setTimeout(function(){
$('.menu-opener').click(function(){
$('#nav').toggleClass('active');
});
let slide = document.querySelector('#nav .active');
slide.addEventListener('click', function(e) {
if (e.target !== slide) return;
$('#nav').removeClass('active');
});
}, 1000);
});
answer is that you need to detect click outside of div you are trying to hide:
$(window).click(function() {
//Hide the menus if visible
});
//stopping above function from running when clicking on #nav itself
$('#nav').click(function(event){
event.stopPropagation();
});
Try this inside setTimeout
$('body').on('click','#nav .active', function(e){
// your logic
})
OR
$( "'#nav .active'" ).bind( "click", function(e) {
// your logic
});
instead of
let slide = document.querySelector('#nav .active');
slide.addEventListener('click', function(e) {
if (e.target !== slide) return;
$('#nav').removeClass('active');
});
Got this working with
$(document).click(function(event) {
if(!$(event.target).closest('#nav').length && !$(event.target).closest(".menu-opener").length)
{
$('#nav').removeClass('active');
}
});

Jquery if div toggled is already visible

i have a div that i want to toggle on click.If div is already visible i dont want my toggle function be executed. Here is my code and for some reasont it's not working propper.
JsFiddle here
<script>
$( document ).ready(function() {
if ($("#toggled").is(":hidden"))
{
$(".test" ).click(function() {
$("#toggled").toggle();
});
}
else
{
}
});
</script>
A lot of work but finally
$( document ).ready(function() {
var indexs = null;
var bindIt = false;
$("ul .test" ).click(function() {
$("#toggled").show();
if($(this).index() == indexs && bindIt == true){
$("#toggled").hide();
bindIt = false;
}else if(bindIt == false){
indexs = $(this).index();
bindIt = true;
}
});
});
JSFIDDLE
You're overthinking this one. If you just want to show the div when a list item is clicked, the show function is all you need:
$(document).ready(function () {
$(".test").click(function () {
$("#toggled").show();
});
});
Here's the updated jsFiddle.
Try using jQuery's one method:
$( document ).ready(function() {
$(".test" ).one('click', function() {
$("#toggled").show();
});
});

How to exclude ID from click function?

I`m new to jQuery and would like to know how I can edit a click function.
Here is what the HTML looks like:
<ul class="result">
<li id="a"></li>
<li></li> //will be added through a loop depending on input
</ul>
So my problem is that when I will click at the li object it will do something. Now I would like to exclude li id="a" from that event. I thought return false; would handle this but it does not.
Here is what the jQuery function looks like:
$('.result li').click(function() {
$('.result li a').click(function (event) {
event.preventDefault();
event.stopPropagation();
});
some further code...
});
I also tried:
$('.result li').click(function() {
$('.result li a').click(function () {
return false;
});
some further code...
});
Thanks alot.
$('.result li:not(#a)').click(function() {
you can do this
$('.result li').click(function() {
if($(this).attr('id')!="your id")
some further code...
});
Try this:
$('.result li').click(function (e) {
if (e.target === this) {
some further code...
}
});
Here, this means the element in the current scope, which is always the li clicked here.
and e.target means the element actually clicked, which can be li or a.
So, in case the element actually clicked is not the li in the current scope, e.target === this return false and nothing happens (no click event is fired) and vice-versa.
A simple if should work:
$('.result li').click(function(ev) {
if (this.id == "a") {
return;
}
// Do your stuff
});
A negation pseudo-class(:not(X)) will do the job. You can get a better idea on negation pseudo-class Here
Now please try with this one
$('.result li:not(#a)').click(function() {
// Your code here...
}

jQuery click() still activates anchor, even though click function returns false

I've got a very basic jQuery tab setup. Everything worked fine, but I needed a hash in the URL to dictate the active tab, so I added a condition to check for the hash. Now when the page loads, it's actually activating the anchor and shifting the page down. Why isn't the "return false;" working?
$(document).ready( function() {
$(".tabs a").click(function() {
$(".tabs a").removeClass("active");
$(".tabs a").addClass("button secondary");
$(this).attr("class","button active");
var href = $(this).attr("href");
$(href).parent().find("> .active").removeClass("active");
$(href).addClass("active");
return false;
});
if(window.location.hash) {
$(".tabs a[href$='"+window.location.hash+"']").click();
} else {
$(".tabs a:eq(0)").click(); //default to first tab
}
});
**
Here are some updates:
**
If I simply enter the actual hash value instead of pull it from window.location.hash, it works perfectly.
$(".tabs a[href$='#Contact2']").click();
Clicking the different tabs DOES NOT shift the page, only when the page loads and automatically clicks the tab based on the hash value.
If I place a conditional and then automatically click without using a a variable within the jquery selector, it works fine, assuming the location hash does not match the hash I'm clicking (strange, I know...)
if(window.location.hash === "#Contact2") {
$(".tabs a[href$='#Contact4']").triggerHandler("click");
} else {
$(".tabs a:eq(0)").click(); //default to first tab
}
This really doesn't make much sense to me. It seems that the only issue is using the window.location.hash within the jquery selector...
Maybe also this code should make your work:
$(".tabs a").click(function(){
// your code
return false;
});
The other way is:
$(".tabs a").click(function(e) {
e.preventDefault();
// your code
});
Your approach is very recursive. Try to avoid running a collection across a collection.
Here are a few snippets from a jQuery 1.7+ implementation that might do what you need.
... initialization
$(body).on("click", ".tabs a", { }, _selectTab);
... some function
_selectTab : function(event) {
$(".tabs a").removeClass(selected); // clear all matches.
$(event.currentTarget).addClass(selected); // something like that.
}
Try preventDefault() instead. Don't forget the e inside .click(function(e).
$(document).ready( function() {
$(".tabs a").each(function() {
$(this).click(function(e) {
e.preventDefault();
$(".tabs a").removeClass("button secondary active");
$(".tabs a").addClass("button secondary");
$(this).attr("class","button active");
var href = $(this).attr("href");
$(href).parent().find("> .active").removeClass("active");
$(href).addClass("active");
});
});
if(window.location.hash) {
$(".tabs a[href$='"+window.location.hash+"']").click();
} else {
$(".tabs a:eq(0)").click(); //default to first tab
}
});
And then chaining some things together...
$(document).ready( function() {
$(".tabs a").each(function() {
$(this).click(function(e) {
e.preventDefault();
$(".tabs a").removeClass("button secondary active").addClass("button secondary");
$(this).attr("class","button active");
var href = $(this).attr("href");
$(href).parent().find("> .active").removeClass("active")
$(href).addClass("active");
});
});
if(window.location.hash) {
$(".tabs a[href$='"+window.location.hash+"']").click();
} else {
$(".tabs a:eq(0)").click(); //default to first tab
}
});
I'm not sure what you're doing here...
$(".tabs a").removeClass("button secondary active")
$(".tabs a").addClass("button secondary");
The second line instantly adds two classes you removed with the first line.
Instead of .click() use .triggerHandler("click")
Also, your click handler needs an e event parameter and you need to call e.preventDefault() instead of the old-school return false.
Lastly, instead of if(window.location.hash) use if(window.location.hash.length > 0)
Pure Javascript Solution to stop all hash default click
var a_tag = document.getElementsByTagName('a');
for (var i = 0; i < a_tag.length; i++) {
a_tag[i].addEventListener('click', function (e) {
var lastChar = this.href.substr(this.href.length - 1);
if (lastChar == "#") {
e.preventDefault();
}
}, false);
}

How do I fire click event if element in array is clicked?

I have an array of DOM elements. If the fourth one is clicked I want to hide the search box. If any of the other ones are clicked I want to show it. How would I do this? I currently have:
var app = {
config: {
tabs: [$("#tab1"), $("#tab2"), $("#tab3"), $("#tab4")],
search: $("#search")
},
showHideSearch: function () {
// Here I need to test if the fourth tab was clicked on then hide();
// else if tabs one through three were clicked show
}
}
app.showHideSearch();
Any help is appreciated. Thank you.
You don't need an array to do this.
$( "#tab4" ).click( function() {
app.config.search.hide();
// $( "#search" ).hide();
});
$( "#tab1, #tab2, #tab3" ).click( function() {
app.config.search.show();
// $( "#search" ).show();
});
$.each(app.config.tabs, function(i, v) {
v.bind('click', function(){
$('#searchbox').show();
if(i==3)
$('#searchbox').hide();
});
});

Categories