jQuery - doesn't react to hasClass() - javascript

The jQuery hasClass() isn't working as it should. When I click on text it should give it a class (and it does), but it doesn't check if it has that class?
There is my code!
$(document).ready(function() {
$('#example').on('click', function() {
$(this).addClass("redText");
});
if ( $('#example').hasClass("redText") ) {
$('#example').addClass("bigText");
}
});
.redText{
color: red;
}
.bigText{
font-size: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="example">Hey</div>

You're only adding the redText class when you click the div. When the if runs that class has not yet been added.
You need to either move the if into your click function, or remove the click function entirely.

I think you might want to do this, but I'm not completely sure;
$(document).ready(function() {
$('#example').on('click', function() {
if ( $('#example').hasClass("redText") ) {
$('#example').addClass("bigText");
}
else{
$(this).addClass("redText");
}
});
This is a total guess, can you please try to explain what it is that you are trying to achieve in more detail.

Your doing your if test only once when the page loads. You'd want to do that test when the element gets clicked and to show that, I've changed addClass to toggleClass so you can keep clicking.
$(document).ready(function() {
$('#example').on('click', function() {
$(this).toggleClass("redText");
if ( $('#example').hasClass("redText") ) {
$('#example').addClass("bigText");
}
});
});
.redText{
color: red;
}
.bigText{
font-size: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="example">Hey</div>

What you are trying to do can be achieved in a single statement like below:
$('#example').on('click', function() {
$(this).addClass("redText bigText");
});
The reason why your code is not working is because: Upon document load, first click listener gets registered. After which if() statement executes which does a lookup on all the redText class elements and finds none, and thus no bigText class gets added. Its not a LIVE listener that you are trying to achieve.

Related

jQuery stopPropagation not stopping click through

I have a panzoom plugin that is working well. When I click on var elem it adds a small div cp_select in the correct location. Then, when I click on that newly created cp_select div, it removes that div. So you can add and remove it accordingly. However, when I click on the cp_select div, it removes it then immediately adds it back in because the click is propagating through. I have tried event.stopPropagation() and event.stopImmediatePropagation() with no luck. Any ideas how to prevent the cp_select firing the map_click(e)?
window.panzoom = panzoom(elem, {
onClick(e) {
map_click(e);
}
})
function map_click(e) {
$(".map_cont").prepend('<div class="cp_select" style="left:'+calc_x+'px ;top:'+calc_y+'px"></div>');
}
$('body').on('click', '.cp_select', function(event) {
event.stopImmediatePropagation()
$(this).remove()
return false;
});
The problem must be specifically with however panzoom is dealing with its onClick, or otherwise in code not shown in the question; if I substitute a plain click event handler on the window in place of your panzoom call, event.stopPropagation() works as expected.
// nonessential code removed and simplified for demo
function map_click() {
$(".map_cont").prepend('<div class="cp_select"></div>');
}
$('body').on('click', '.cp_select', function(event) {
$(this).remove();
event.stopPropagation();
});
window.onclick = map_click // stand-in for your panzoom function
.cp_select {
border: 3px solid;
height: 20px; width: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
(click anywhere)
<div class="map_cont"></div>

Using JS How to call click function once only which will be equivalent to .one jQuery

Hello could someone help me? I'm having trouble transforming this part of my code to JS:
$(".custom-select-trigger").on("click", function() {
$('html').one('click',function() {
$(".custom-select").removeClass("opened");
});
$(this).parents(".custom-select").toggleClass("opened");
event.stopPropagation();
});
I have it so far:
const customSelectTrigger = document.querySelector(".custom-select-trigger");
const customSelect = document.querySelector(".custom-select");
function showOptions(e) {
e.preventDefault();
customSelect.classList.toggle("opened");
e.stopPropagation();
}
but I'm not able to do this part for javascript:
$('html').one('click',function() {
$(".custom-select").removeClass("opened");
});
Here is working code for to remove class opened from your custom select when you press anywhere in the DOM.
You need to use JS addEventListener and click function to do this.
To remove class from an element we can use .remove function and getting the classList of your element by querySelector which will .custom-select
Edit: If you just want to use the click function once only per DOM load. Then setting setting the args { once: true } will only invoke the function once.
I have recreated your example and its working.
Run snippet below.
//Getting HTML element
const htmlElement = document.querySelector("html");
//Getting element where to remove the class from
const customSelect = document.querySelector(".custom-select");
//Adding eventlistener to remove class opened from classList
htmlElement.addEventListener("click", function(e) {
customSelect.classList.remove("opened");
console.log('Class Removed')
e.preventDefault();
},{ once: true });
.opened {
background-color: red;
}
<html>
<h3>
Click anywhere on the DOM to remove class from Custom select
</h3>
<div class="custom-select opened">
My Custom Select
</div>
</html>

Jquery If/Then in Click Function?

This is what I want it to do...
When div called 'bd' is clicked > check if the div with id of 'ump' has a class of 'active' >
if it does, get div with class of 'brandDump' and slide it up slowly, hide it, and remove the class of 'active' > else, take the div with class 'brandDump' and slide it down, show it, and add class of 'active'
Nothing is happening when I click div.bd. What am I doing wrong?
Fiddle link and code below.
http://jsfiddle.net/K2V8f/36/
<div class="bd">cool</div>
<div class="brandDump" id="ump">works</div>
<div>shape</div>
.brandDump {
background-color:#fff;
width:100px;
display:none;
}
.bd {
width:100px;
height:100px;
background-color:#000;
}
$(".bd").click(function () {
if ("#ump".hasClass("active")) {
$(".brandDump").slideUp("slow");
$(".brandDump").hide();
$(".brandDump").removeClass("active");
} else {
$(".brandDump").slideDown("slow");
$(".brandDump").show();
$(".brandDump").addClass("active");
}
});
Updated fiddle
You need to use callbacks when the slideUp finishes.
$(".bd").click(function () {
if ($("#ump").hasClass("active")) {
$(".brandDump").slideUp("slow", function () {
$(".brandDump").removeClass("active");
});
} else {
$(".brandDump").slideDown("slow", function () {
$(".brandDump").addClass("active");
});
}
});
Also there was an error with ("#ump")... should have been $("#ump")
The problem is that you had:
"#ump".hasClass(...
...when you should've had:
$("#ump").hasClass(...
But note also that the .slideUp() and .slideDown() methods hide and show your element(s) so you don't need to call .hide() and .show() as well. Also it is more efficient to chain jQuery methods together if you want them to operate on the same element:
$(".bd").click(function () {
if ($("#ump").hasClass("active")) {
$(".brandDump").slideUp("slow")
.removeClass("active");
} else {
$(".brandDump").slideDown("slow")
.addClass("active");
}
});
Demo: http://jsfiddle.net/K2V8f/50/
"check if the div with id of 'ump' has a class of 'active' > if it does, get div with class of 'brandDump' and slide it up slowly"
The div with id ump is the same div as the one with class brandDump. I'm not sure why you're talking about them as if they're two different divs when in fact your code seems to then use the #ump and .brandDump selectors interchangeably to select the one div, but if you treat them as one more consistently you can cut your function down to one line:
$(".bd").click(function () {
$(".brandDump").slideToggle("slow").toggleClass("active");
});
Demo: http://jsfiddle.net/K2V8f/51/

If jQuery has Class do this action

I am trying to check whether or not a particular element has been clicked but am having trouble doing so. Here is my HTML:
<div id="my_special_id" class="switch switch-small has-switch" data-on="success" data-off="danger">
<div class="switch-on switch-animate"><input type="checkbox" checked="" class="toggle">
<span class="switch-left switch-small switch-success">ON</span>
<label class="switch-small"> </label>
<span class="switch-right switch-small switch-danger">OFF</span>
</div>
</div>
Here is my jQuery:
<script type="text/javascript">
$(document).ready(function() {
$('#my_special_id').click(function() {
if ($('#my_special_id div:first-child').hasClass('switch-on')) {
window.alert('ON!');
}
});
});
</script>
I am guessing that my id "my_special_id" is not what is actually being clicked?
I guess click event should have event parameter.
$(document).ready(function() {
$('#my_special_id').click(function(e) {
if (e.target check condition) {
window.alert('ON!');
}
});
});
parameter 'e' above specified is the event object that has all info about click event.
so if u check all info under 'e.tartget', u will be able to find out which one is clicked.
Hope it's helpful for you.
Cheers :)
Since you are looking for a alert when the checkbox is clicked
$(document).ready(function() {
$('#my_special_id input.toggle').click(function() {
if ($('#my_special_id div:first-child').hasClass('switch-on')) {
window.alert('ON!');
}
});
});
Demo: Fiddle
Simply put alert when you click on that particular class switch-on
<script type="text/javascript">
$(document).ready(function() {
$('#my_special_id div:first-child .switch-on').on('click',function() {
window.alert('ON!');
});
});
</script>
Or even try like
$(document).ready(function() {
$('#my_special_id').click(function() {
if ($(this + 'div:first-child').hasClass('switch-on')) {
window.alert('ON!');
}
});
});
This JavaScript works for me.
$(document).ready(function() {
$('#my_special_id').click(function() {
if ($('#my_special_id div:first-child').hasClass('switch-on')) {
alert("On!");
}
});
});
You are sure you have JQuery?
Your code looks fine I think either you have a syntax error somewhere else or you do not have JQuert.
does this alert?
$(document).ready(function() {
alert("Jquery works");
});
The click event will trigger to whatever you're bound do. the only time you'd have to be worried is if you bound to both a parent and child (e.g. you had listed #my_special_id,.switch-small--then you'd have to look at e.target).
With that said, you can use scope to limit how jQuery finds the div:first-child. I'm not 100% sure what you're after, but the below appears to do what you're after:
$(document).ready(function() {
$('#my_special_id').click(function() {
// look for div:first-child within `this` (where `this=#my_special_id`
// per the .click selector above)
if ($('div:first-child',this).hasClass('switch-on')) {
window.alert('ON!');
}
});
});
If you're looking to bind to the on/off separately, you may want to change it around a bit. we can still check for .switch-on, just have to traverse differently:
// here we bind to the on/off buttons and not the container
$('#my_special_id .switch-small').click(function(){
// you want the facsimilee of `div:first-child`, so (because we're now
// within that node, we use .parent() to get back up to it
var $firstChild = $(this).parent();
if ($parent.hasClass('switch-on')){
alert('ON!');
}
});

Is it possible to write onFocus/lostFocus handler for a DIV using JS or jQuery?

I have a div and when the user clicks the div a function should be called. And when the user clicks something else (anything other than this div) another function should be called.
So basically i need to have onFocus() and lostFocus() function calls associated with this DIV. Is it available in JavaScript or even in jQuery?
Thanks.
You need to add tabindex attribute to div :
$("#mydiv").focusin(function() {
$("#mydiv").css("background", "red");
});
$("#mydiv").focusout(function() {
$("#mydiv").css("background", "white");
});
#mydiv {
width: 50px;
height: 50px;
border: 1px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="mydiv" tabindex="100"></div>
<div id="anotherdiv"></div>
Focus do not work on DIV : http://api.jquery.com/focus/
ALso good read: jquery : focus to div is not working
If you want to focus a div or anything normally can't be focused, set the tag's tabindex to -1 first.
eg: $("div#header").attr("tabindex",-1).focus();
Not sure if this solution suits your web page, but you could use JQuery on() to attach a click event to the body element and delegate it to child div's. Then in your event handler, test the id attribute and handle as such; something like:
$(body).on("click", "div", function (evt) {
if ($(this).attr("id") == "innerDiv") {
handle inner div click here
} else {
hanlde out div click here
{
}
Hope this helps...
Sure.
$("#your-div-id").focusin(function() {
// code here
});
$("#your-div-id").focusout(function() {
// code here
});

Categories

Resources