hasClass doesn't function as it should - javascript

I have a list of li items and would like to trigger a button click if 2 classes are found.
When a list item has 2 classes, I would like to trigger the btn with a click. Can you guys take a look for me?
The code:
<script type="text/javascript">
$(document).ready(function(){
var $html = $("#my-div ul li");
if ($html.hasClass("current") || $html.hasClass("extra")) {
$(".btn-1 a").click();}
else if ($html.hasClass("current") || $html.hasClass("extra2")) {
$(".btn-2 a").click();}
});
</script>
So one list item has class current + extra, and the other list item hasClass current + extra2.
Any idea what I am doing wrong here?
EDIT: Currently it does not work as should be.
It currently will always trigger ".btn-1" to click and does not look at the other statements. I think it just looks at the "current" class and not if also the "extra" or "extra2" class is in the same li item.

Try this:
<script type="text/javascript">
$(document).ready(function(){
var $html = $("#my-div ul li.current");
if ($html.hasClass("extra")) {
$(".btn-1 a a").click();}
else if ($html.hasClass("extra2")) {
$(".btn-2 a").click();}
});
</script>
The problem is, when you do $html.hasClass("current") || .. it would always evalutate to true and would not go to the else clause when node has a class current

You are making a comparison of a or b where you need a and b so change it to this:
<script type="text/javascript">
$(document).ready(function(){
var $html = $("#my-div ul li");
if ($html.hasClass("current") && $html.hasClass("extra")) {
$(".btn-1 a a").click();}
else if ($html.hasClass("current") && $html.hasClass("extra2")) {
$(".btn-2 a").click();}
});
</script>

Try replacing
$html.hasClass("current") || $html.hasClass("extra")
with
$html.hasClass("current") && $html.hasClass("extra")
and also
$html.hasClass("current") || $html.hasClass("extra2")
with
$html.hasClass("current") && $html.hasClass("extra2")

The original root of the problem is that you're using or (||) and not and (&&) when testing for classes. You're asking "if li has class current OR extra".
However, you can also refactor it a bit and make it a little cleaner as well:
// first, grab the <li> marked as current
var $current = $('#my-div ul li.current');
// test if we have a match and proceed
if ($current.size()){
// cache the final target selector (by initializing it to `false` we
// can later test and only execute the click when we have a match)
var target = false;
// now get in to second-level classes (can use either `.is()` or
// `.hasClass()` (thought I'd show an alternative method as well))
if ($current.hasClass('.extra')) target = '.btn-1 a a';
else if ($current.hasClass('.extra2')) target = '.btn-2 a';
// else if ($current.hasClass('...')) target = '...'; // more tests
// see if we found a match and click it
if (target) $(target).click();
}

Related

How to run only one function if we have multiple class

So. to begin with,
I am writing my eventlisteners in this way.
document.addEventListener('click',(e)=>{
const element = e.target;
if(element.classList.contains('classOne'){
fire_function_one();
}
if(element.classList.contains('classTwo'){
fire_function_two();
}
});
I have a div like follows
<div class='classOne classTwo'>Something</div>
So what I want to achieve is,
When our div has classOne, I want to fire 'fire_function_one()', However when our div has both classOne and ClassTwo, I want to fire 'fire_function_two()' but I dont want to run 'fire_function_one()'.
What I have tried,
event.stopPropogation; //Not working
event.preventDefault; //Not working
if(element.classList.contains('classTwo' && !element.classList.contains('classOne'){
fire_function_two();
//Doesnt acheive what I want
}
Change the Order of your condition and use else if statement.
document.addEventListener('click',(e)=>{
const element = e.target;
if(element.classList.contains('classTwo'){
fire_function_two();
}
else if(element.classList.contains('classOne'){
fire_function_one();
}
});
If you are sure that the element can have classOne or both classTwo and classOne, you can just change the order and use else if statement:
document.addEventListener('click',(e)=>{
const element = e.target;
if(element.classList.contains('classTwo'){
fire_function_two();
} else if(element.classList.contains('classOne'){
fire_function_one();
}
});
You need to write click on element as below.
var eleOne = document.getElementsByClassName('classOne')
if(eleOne.length > 0) {
var currentEleOne = eleOne[0];
currentEleOne.onclick = function () {
// Click code for classOne
}
}
var eleTwo = document.getElementsByClassName('classTwo')
if(eleTwo.length > 0) {
var currentEleTwo = eleTwo[0];
currentEleTwo.onclick = function () {
// Click code for classTwo
}
}
Here you have two cases,
When both classes are present, fire only class two
If only class one is present, fire class one
So, First check with if whether both classes are present or not. If true then fire class two. Otherwise inside else if, check if class one is present and if this condition is met, fire class one.
document.addEventListener('click', function(e) {
const element = e.target;
if (element.classList.contains('classTwo')) {
console.log("Fire class two");
} else if (element.classList.contains('classOne')) {
console.log("Fire class one");
}
});
<div class='classOne classTwo'>Something 1 2</div>
<div class='classOne'>Something 1</div>
You could try a simple ternary like this:
document.addEventListener('click', (e) => {
const element = e.target;
element.classList.contains('classTwo') ? fire_function_two() : fire_function_one();
});
If the classList contains 'classTwo' then run fire_function_two() else fire_function_one()

check if selection contains div Jquery

t = window.getSelection();
if ((t) contains (div.class)){
//do something
}
How can I do that WHILE selecting the text? Not after the text is selected(eg: after I release the click). I plan to remove selection (document.getSelection().removeAllRanges(); ) if I find a div with a specific class.
Thanks!
I already have a mouseup function. if that is what I need, I can add new code to that...
To check if the attribute exists, just use find on your object called "t" and look for any div. If you find something, attribute length will be > 0:
if(t.find("div").length > 0) {
//do something
}
If you want to trigger your code before the selection is over you need to use an event that triggers before like mousedown.
$(document).on("mouseup", function() {
var t = window.getSelection();
if(t.length > 0) { //This should catch the problem when there is nothing selected
var obj = t.find("div[class=xy]");
if(obj.length > 0) { //my div with class xy was found!
//do something
}
}
});

Selecting, Deleting jQuery based on wildcard

What I would like is if there is NOT a word "link" in the href "www.1link.com" all the top classes 1-6 is changed to classdefault.
Also a different code that does the same thing except of adding "defaultclass" it removes all the classes 1-6 empty.
This is what I've tried so far and it hasn't worked
http://jsfiddle.net/yLxXn/2/
$(document).ready(function() {
if ($('a[href$="link"]')) {
// do something here
$("[class^=content]").attr("class", "classdefault");
}
});
Try something like this :
if ($('a').attr('href').indexOf('link') != -1) {
// other code
}
UPDATE
If you want this to happen if it does not contain "link", change >= to <=. As following:
For replacing all classes:
$('div').find('a').each(function(){
var hrefString = $(this).attr('href');
if (hrefString.indexOf("link") <= 0){
$('[class^=class]').attr('class', 'classdefault');
}
});
For removing all classes:
$('div').find('a').each(function(){
var hrefString = $(this).attr('href');
if (hrefString.indexOf("link") <= 0){
$('[class^=class]').removeClass();
}
});

jQuery - hiding an element when on a certain page

I have this wizard step form that I simulated with <ul> list items by overlapping inactive <li> items with absolute positioning.
The wizard form is working as desired except that I want to hide next or previous button on a certain step.
This is my logic in jQuery but it doesn't do any good.
if (index === 0) {
$('#prev').addClass(invisible);
$('#prev').removeClass(visible);
} else if (index === 1) {
$('#prev').addClass(visible);
$('#prev').removeClass(invisible);
} else {
$('#next').addClass(invisible);
}
To get the index value I used eq() chained on a current step element like the following
var current;
var index = 0;
$(function () {
current = $('.pg-wrapper').find('.current');
$('#next').on('click', function() {
if (current.next().length===0) return;
current.next().addClass('current').show();
current.removeClass('current').hide();
navstep.next().addClass('active');
navstep.removeClass('active');
current = current.next();
navstep = navstep.next();
index = current.eq();
});
I tried to isolate it as much as possible but my full code will give you a better idea.
If you would care to assist please check my JS BIN
There were several issues
you used .eq instead of index
you were missing quotes around the class names
your navigation logic was flawed
no need to have two classes to change visibility
I believe the following is an improvement, but let me know if you have questions.
I added class="navBut" to the prev/next and rewrote the setting of the visibility
Live Demo
var current;
var navstep;
$(function () {
current = $('.pg-wrapper').find('.current');
navstep=$('.nav-step').find('.active');
$('.pg-wrapper div').not(current).hide();
setBut(current);
$('.navBut').on('click', function() {
var next = this.id=="next";
if (next) {
if (current.next().length===0) return;
current.next().addClass('current').show();
navstep.next().addClass('active');
}
else {
if (current.prev().length===0) return;
current.prev().addClass('current').show();
navstep.prev().addClass('active');
}
current.removeClass('current').hide();
navstep.removeClass('active');
current = (next)?current.next():current.prev();
navstep = (next)?navstep.next():navstep.prev();
setBut(current);
});
});
function setBut(current) {
var index=current.index();
var max = current.parent().children().length-1;
$('#prev').toggleClass("invisible",index<1);
$('#next').toggleClass("invisible",index>=max);
}
The eq function will not give you the index, for that you need to use the index() function.
I have not looked at the whole code but shouldn't your class assignemnts look like:
$('#prev').addClass('invisible');
$('#prev').removeClass('visible');
i.e. with quotes around the class names? And is it really necessary to have a class visible? Assigning and removing the class invisible should easily do the job (provided the right styles have been set for this class).
You should make 4 modifications.
1) Use .index() instead of .eq();
2) Add a function changeIndex which changes the class depends on the index and call it on click of prev and next.
3) add quotes to invisible and visible
4) There is a bug in your logic, try going to 3rd step and come back to 1st step. Both buttons will disappear. So you have to make next button visible if index = 0
Here is the demo :
http://jsfiddle.net/ChaitanyaMunipalle/9SzWB/
Use index() function instead of eq() because eq() will return object and index() will return the integer value.
DEMO HERE
var current;
var navstep;
var index = 0;
$(function () {
current = $('.pg-wrapper').find('.current');
navstep=$('.nav-step').find('.active');
$('.pg-wrapper div').not(current).hide();
}(jQuery));
$('#next').on('click', function() {
if (current.next().length===0) return;
current.next().addClass('current').show();
current.removeClass('current').hide();
navstep.next().addClass('active');
navstep.removeClass('active');
current = current.next();
navstep = navstep.next();
index = current.index();
change_step(index)
});
$('#prev').on('click', function() {
if (current.prev().length===0) return;
current.prev().addClass('current').show();
current.removeClass('current').hide();
navstep.prev().addClass('active');
navstep.removeClass('active');
current = current.prev();
navstep = navstep.prev();
index = current.index();
change_step(index)
});
function change_step(value)
{
if (value === 0) {
$('#prev').hide();
$('#next').show();
} else if (value === 1) {
$('#prev').show();
$('#next').show();
} else {
$('#next').hide();
$('#prev').show();
}
}

window.location.href.match Not Working

Here is the code:
$(function() {
var pathname = (window.location.href.match(/[^\/]+$/)[0]);
$('#menu dl dd a#toparrow').each(function() {
if ($(this).attr('href') == pathname) {
$(this).addClass('currenttop');
}
});
});
Here is a link to my website: http://bluraymoviestore.com
The purpose of the script is to make the arrow image stay on the current page, like it does when you first click to the categories.
The script works when I'm clicked on the parent page, but when I click to the next page under the same category, the script no longer works (example: works with /bluraynewreleases but not /bluraynewreleases-2625374011-rc-2-new_releases.html). What do I need to add to the code to make it work?
Your regex doesn't match anything so it throws an error when you attempt to access [0] on it. Assuming your regex is correct this should fix the issue.
$(function(){
var matches = window.location.href.match(/[^\/]+$/);
if (matches && matches.length) {
var pathname = (matches[0]);
$('#menu dl dd a#toparrow').each(function() {
if ($(this).attr('href') == pathname) {
$(this).addClass('currenttop');
}
});
}
});

Categories

Resources