jQuery if and $(this) confusion - javascript

Something that has been bugging me for a while.
JavaScript
$('.video-tab-container ul li a').click(function(e) {
var thisClass = $(this).attr('class');
console.log(thisClass);
if ( $('.video-container .video').is('.' + thisClass) ) {
$(this).addClass('test');
}
e.preventDefault();
});
HTML
<div class="video-tab-container clearfix">
<ul>
<li><a class="chinese" href="#">Chinese</a></li>
<li><a class="thai" href="#">Thai</a></li>
<li><a class="english" href="#">English</a></li>
</ul>
</div>
<div class="video-container">
<div class="video chinese"></div>
<div class="video thai"></div>
<div class="video english"></div>
</div>
Within the if statement, how do I make $(this) the element within the if statement? So, if the statement is true, the class test is added to the .video with the corresponding class? Maybe I am doing this all wrong.

You need to use:
$(this).closest('.video-tab-container').next()
.find('.video.' + thisClass).addClass('test')
.siblings('.video').removeClass('test');
instead of:
$(this).addClass('test');
because currently $(this) is treated as your clicked anchor.
Fiddle Demo

I think replacing your if statement with this:
$('.video-container .video.' + thisClass).addClass('test');
will do what you're trying to do. Like the commenters above said, the "if" statement doesn't change what "this" refers to.

The reference to this isn't going to change just because it's within an if statement.
If you want the reference to this to change the statement needs to be written like this:
$('.video-tab-container ul li a').click(function(e) {
var thisClass = $(this).attr('class');
console.log(thisClass);
$('.video-container .video').each(function(){
var $this = $(this);
if ($this.is('.' + thisClass) ) {
$this.addClass('test');
}
})
e.preventDefault();
});

$('.video-tab-container ul li a').click(function(e) {
var thisClass, video;
thisClass = $(this).attr('class');
console.log(thisClass);
if ((video = $('.video-container .video.' + thisClass)).length !== 0) {
$(video).addClass('test');
}
e.preventDefault();
});

Related

Active navigation class based on current URL problem

I have the following HTML menu:
<div class="nav">
<ul>
<li class="first">Home</li>
<li>Something</li>
<li>Else</li>
<li class="last">Random</li>
</ul>
<ul style="float:right;">
<li class="first last">News</li>
</ul>
</div>
</div>
And then I have this code:
jQuery(function($){
var current = location.pathname;
$('.nav ul li a').each(function(){
var $this = $(this);
// if the current path is like this link, make it active
if($this.attr('href').indexOf(current) !== -1){
$this.addClass('active');
}
})
})
The code is working great, but it has a problem. For example, if I see the Home page (www.example.com) then all of the menu links receives the active class. Another problem would be that it works great for www.example.com/something but it doesn't keep it active if I go to www.example.com/something/1 etc. Any idea how to fix this? Thanks in advance!
For home page add extra class 'default' in list like.
<li class="first default">Home</li>
jquery code.
jQuery(function($){
var current = location.pathname;
console.log(current);
//remove the active class from list item.
$('.nav ul li a').removeClass('active');
if(current != '/'){
$('.nav ul li a').each(function(){
var $this = $(this);
// if the current path is like this link, make it active
if(current.indexOf($this.attr('href')) !== -1 && $this.attr('href') != '/'){
$this.addClass('active');
}
})
}else{
console.log('home');
$('.default a').addClass('active');
}
})
Use the below jQuery code to add active class:
$(function() {
var pgurl = window.location.href.substr(window.location.href
.lastIndexOf("/") + 1);
$(".nav ul li a").each(function() {
if ($(this).attr("href") == pgurl || $(this).attr("href") == '')
$(this).addClass("active");
})
});
By using indexOf(), you are checking if the link's target is the same the current location.
What you want is not "the same URL" but "the same pattern", so I would tend to use a regular expression :
let re = new RegExp("^" + $(this).attr("href") + ".*");
if (re.test($current)) {
$(this).addClass("active");
}
Note that this would force you to create a separate solution for your link to the main page, else it would always be active.

How to use addClass and removeClass repeatedly on a single element?

So what I want to achieve is just change the classes of a HTML link on every click like this:
Remove .first class if it is present, then add .second class
Remove .second class if it is present, then add .third class
Remove .third class if it is present, then add .fourth class
And so forth...
No luck so far. What could I be doing wrong?
Here's the single line of HTML code where I'm trying my jQuery code on:
<a class="first" href="#">Test 1</a>
Here's my jQuery:
$( "#menu li a.first" ).click(function() {
$( "#menu li a.first" ).removeClass("first").addClass("second");
}
$( "#menu li a.second" ).click(function() {
$( "#menu li a.second" ).removeClass("second").addClass("third");
}
$( "#menu li a.third" ).click(function() {
$( "#menu li a.second" ).removeClass("third").addClass("fourth");
}
Thanks in advance!
The problem is you're trying to attach the event handler before it even has the class second or third.
Besides this approach is pretty verbose. I suggest simply providing an array of classes. Like so:
var classNames = ['first', 'second', 'third'];
Then add a different identifier to the button, for instance add a class class-changer. And attach the following event handler.
$('.class-changer').on('click', function() {
var $el = $(this)
for (var i= 0; i < classNames.length; i++) {
if ($el.hasClass(classNames[i]) && classNames[i+1]) {
$el.removeClass(classNames[i]).addClass(classNames[i+1]);
break;
}
}
});
Put all classes in an array and on click of the link add class one by one like following.
var classes = ["first", "second", "third", "fourth"];
$("#menu li a").click(function () {
var index = classes.indexOf(this.className);
var newIndex = (index + 1) % classes.length; //return to first after reaching last
$(this).removeClass(classes[index]).addClass(classes[newIndex]);
});
.first { color: red; }
.second { color: green; }
.third { color: blue; }
.fourth { color: purple; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="menu">
<li>
<a class="first" href="#">Test 1</a>
</li>
</ul>
Assuming you actually only have 1 link whose state you're trying to change, instead of a bunch of links in your menu that you want to ALL be moved from ".first" to ".second" when one is clicked, I would suggest this as the most idiomatic way (pun not intended).
// Only select the menu once
var $menu = $('#menu');
// Delegate to elements with the correct class.
// Specifying the "li a" is probably unnecessary,
// unless you have other elements with the same classes in "#menu".
$menu.on('click', '.first', function(e) {
// Inside a jQuery event handler,
// `this` refers to the element that triggered the event.
// If the event is delegated, it's the delegation target
// (".first" in this instance), not the bound element ("#menu").
$(this).removeClass('first').addClass('second');
});
$menu.on('click', '.second', function(e) {
$(this).removeClass('second').addClass('third');
});
$menu.on('click', '.third', function(e) {
$(this).removeClass('third').addClass('fourth');
});
Resources:
Why should you cache jQuery selectors?
Event Delegation in jQuery
"this" in jQuery events
General jQuery Optimization
You can do it with the usage of .data()
HTML:
<a class="first" href="#" id="test">Test 1</a>
JS:
$(".first").data("classes",["one","two","three","four"]).click(function() {
var elem = $(this);
var cnt = (elem.data("cnt") || 0)
var classes = elem.data("classes");
elem.removeClass().addClass(classes[cnt % classes.length] + " first").data("cnt",++cnt);
});
Demo
$(".first").data("classes",["one","two","three","four"]).click(function() {
var elem = $(this);
var cnt = (elem.data("cnt") || 0)
var classes = elem.data("classes");
elem.removeClass().addClass(classes[cnt % classes.length] + " first").data("cnt",++cnt);
});
.one{
color:red;
}
.two{
color:yellow;
}
.three{
color:green;
}
.four{
color:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<a class="first" href="#" id="test">Test 1</a>
Not sure if this would solve your issue but I would shoot for a conditional statement and only one delegated event listener:
$("#menu li").on("click", "a", function () {
if ($(this).hasClass("first")) {
$(this).removeClass("first").addClass("second");
} else if ($(this).hasClass("second")) {
$(this).removeClass("second").addClass("third");
}
// etc...
});
If you want to bind an event the selected element must exist previously.
To bind an event handler to elements that does not yet exist (ex. dynamically created or modified) you can do this:
$(document).on('click', '#menu li a.first', function() {
$( "#menu li a.first" ).removeClass("first").addClass("second");
});
$(document).on('click', '#menu li a.second', function() {
$( "#menu li a.second" ).removeClass("second").addClass("third");
});
$(document).on('click', '#menu li a.third', function() {
$( "#menu li a.third" ).removeClass("third").addClass("fourth");
});
<a class="changable first" href="#">Test 1</a>
$( ".changable" ).click(function(event) {
classes = ['first','second','third','fourth']
changed=false
for (c in classes){
if (event.target.classList.contains(classes[c]) && changed==false){
$(this).removeClass((classes[c]));
index_to_add=classes.indexOf(classes[c])+1
class_to_add=classes[index_to_add]
$(this).addClass(class_to_add);
changed=true;
}
}
});
Okay so there is a few workaround for this, which wasn't mentioned yet.
You can use Javascript object for this not just array. Object could make it easier if you want a chain instead of list.
var classNames = {first:'second', second:'third', third:'fourth'};
$('#menu li a').on('click', function() {
if(typeof classNames[this.className] !== 'undefined'){
this.className = classNames[this.className];
}
});
Second method is to use .on('click', [selector], handler) instead click which can handle dynamicly loaded, added or changed elements.
$('#menu li').on('click', 'a.first', function() {
$(this).removeClass("first").addClass("second");
});
$('#menu li').on('click', 'a.second', function() {
$(this).removeClass("second").addClass("third");
});
$('#menu li').on('click', 'a.third', function() {
$(this).removeClass("third").addClass("fourth");
});
Not even close to perfect but still a working solution.
You can use if .. else or switch .. case inside a function to create a decision tree.
So basically there is a lot of solution. Pick the best.
Try binding event to parent,
My try,
var $classes = ['first', 'second', 'third'];
$(function(){
$('#subject').click(function(){
current = $(this).find('a:first');
index = $.inArray(current.attr('class'), $classes);
if($classes.length > index+1)
current.removeClass($classes[index]).addClass($classes[index+1])
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id='subject'>
<a class="first" href="#">Test 1</a>
</div>
No, you can't. As JavaScript only runs after the page loads ( if you put them inside the $( document ).ready() function ), further functions down below will never be executed. It can only detect the <a class="first" href="#">Test 1</a> but not the <a class="second" href="#">Test 1</a> because the <a class="second" href="#">Test 1</a> are generated after the page loads and, therefore, will never be executed, unless you are using Ajax.
Update: This can be done. Please see #i3b13's comment below.

How to hide multiple jQuery toggle() when I click outside of the menu?

I have multiple toggle elements on my page. I am trying to get them closed when clicking on the outside of the div element. the script i have now works veyr well with multiple elements but it also closes the div when clicking on inside of the div
<ul>
<li class="menuContainer">
<a class="top" href="#">Menu</a>
<div class="sub">
<a class="top" href="google.com">item in dropdown menu with valid url when clicked here div.sub should stay close</a>
</div>
</li>
<li class="menuContainer">
<a class="top" href="#">Menu</a>
<div class="sub">
<a class="top" href="#">item in dropdown menu when clicked here div.sub should stay open</a>
</div>
</li>
$(document).ready(function(){
$('li.menuContainer').each(function() {
var $dropdown = $(this);
$("a.top", $dropdown).click(function(e) {
e.preventDefault();
$div = $("div.sub", $dropdown);
$div.toggle();
$("li.menuContainer div.sub").not($div).hide();
$( "#effect" ).hide();
return false;
});
$("li.menuContainer div.sub").on("click", function (event) {
event.stopPropagation();
});
});
$(document).on("click", function (){
$("li.menuContainer div.sub").hide();
});
});
what i want to do is to stop closing div when clicked inside of it. Any help please?
I think you are looking for e.stopPropagation();. Use it in an event on the child items.
This will stop the event from propagating to the parent div.
In your code the problem is inside the following function, now corrected:
$('html').click(function(event){
var ele = event.target.tagName + '.' + event.target.className;
if (ele != 'DIV.sub') {
$("li.menuContainer div.sub").hide();
}
});
Like you can see now when you click on whatever html element a check is done to prevent the undesired action.
use this code
$("li.menuContainer > a.top").click(function(e) {
e.preventDefault();
$div = $(this).next("div.sub");
$("li.menuContainer div.sub").not($div).slideUp();
$div.slideDown();
});
instead of
$('li.menuContainer').each(function() {
var $dropdown = $(this);
$("a.top", $dropdown).click(function(e) {
e.preventDefault();
$div = $("div.sub", $dropdown);
$div.toggle();
$("li.menuContainer div.sub").not($div).hide();
return false;
});
});
and about
$('html').click(function(){
$("li.menuContainer div.sub").hide();
});
you can use
$(window).on('click',function(e){
if (!$("li.menuContainer").is(e.target) // if the target of the click isn't the container...
&& $("li.menuContainer").has(e.target).length === 0) // ... nor a descendant of the container
{
$("li.menuContainer div.sub").slideUp();
}
});
Working Demo
Update:
$("div.sub > a.top").on('click',function(e) {
e.preventDefault(); // prevent page from reloading
e.stopPropagation(); // prevent parent click
alert('Here We Are :)');
});
Working Demo

Matching text within a parent element

I am attempting to check if 2 divs contain the same text, and if they do then add a style to the parent div.
I have this working fine with the below code, but my problem is that the divs are all looking for a match and not just the divs that are in the parent? if you look at the below
<div class="infobox">
<div class="date">8</div>
<div class="secdate">8</div>
</div>
<div class="infobox">
<div class="date">1</div>
<div class="secdate">11</div>
</div>
<div class="infobox">
<div class="date">8</div>
<div class="secdate">11</div>
</div>
and the jQuery
jQuery(function ($) {
$('.date').each(function () {
var myhtml = $(this).html().split(' ')[0];
var ele = $(this);
$('.secdate').each(function () {
myhtml == $(this).html().split(' ')[0] ? $(ele).parent().css('background', '#ffff00') : ""
})
})
});
Fiddle
the third div is having the style applied, which it shouldn't as the 2 divs within don't match?
This seems much simpler:
$('.infobox').each(function () {
if ($(this).find('.date').text() == $(this).find('.secdate').text()) $(this).css('background', '#ffff00')
})
jsFiddle example
Loop over the parent (infobox) and just compare the text of the date child to the secdate child.
Seems like it should be simpler:
jQuery(function ($) {
$('.date').each(function () {
var dateText = $(this).text();
var secdateText = $(this).next('.secdate').text();
if (dateText == secdateText) {
$(this).parent().css('background', '#ffff00');
}
});
});
Fiddle
I changed things a little bit:
$(document).ready(function(){
$('.infobox').each(function () {
if( $(this).children('.date').html() == $(this).children('.secdate').html() )
$(this).css('background', '#ffff00');
});
});
This way you don't even need a loop.
I tested here and it works like charm :)
Hope it helps

.addClass to element adds a styling then removes, how do I fix

I have a code
var prev;
function addClass( classname, element ) {
prev = cn;
var cn = document.getElementById(element);
$(cn).addClass("selected");
}
The element in the dom look like this:
<div class="arrowgreen">
<ul>
<li>Manager</li>
<li>Planner</li>
<li>Administrator</li>
</ul>
</div>
For 'arrowgreen' I have a styling which changes the li styling on rollover and click.
When an element is clicked on, I want to apply the 'selected' classname to the element.
It does this for a split second and then reverts back.
The css looks like
.arrowgreen li a.selected{
color: #26370A;
background-position: 100% -64px;
}
Working jsFiddle Demo
In usage of $ in your code, I see that you are using jQuery.
There is no need to set onclick internally.
Let's jQuery handle it for you:
// wait for dom ready
$(function () {
// when user clicks on elements
$('.arrowgreen li a').on('click', function (e) {
// prevent default the behaviour of link
e.preventDefault();
// remove old `selected` classes from elements
$('.arrowgreen li a').removeClass('selected');
// add class `selected` to current element
$(this).addClass('selected');
});
});
Working JSFiddle
There was an error in your HTML, a " that opened a new string after onclick.
var prev;
function addClass(classname, element) {
var cn = document.getElementById(element);
prev = cn; //does nothing useful really
$(cn).addClass("selected");
}
<div class="arrowgreen">
<ul>
<li>Manager
</li>
<li>Planner
</li>
<li>Administrator
</li>
</ul>
</div>
Remember to include jQuery in your page!
There is a way to do this without jQuery anyway:
function addClass(classname, element) {
var cn = document.getElementById(element);
prev = cn; //does nothing useful really
cn.className += " " + classname;
}
Similar way to do it:
(function ($) {
$('.arrowgreen > ul > li > a').on('click', function (e) {
e.preventDefault();
$(this).addClass('selected').siblings().removeClass('selected');
});
}(jQuery));

Categories