This should be a quickie!
I need to differentiate between two elements on click by their class name.. for example
html:
<p class='p1'>paragraph element</p>
<p class='p2'>paragraph element</p>
jquery:
$('p').on('click', function() {
if ($(this).attr('class', 'p1') {
callThisFunction();
} else {
doNothing();
}
});
if ($(this).is(".p1")) {
or
if ($(this).hasClass("p1")) {
$(this).attr("class", "p1") actually sets the class attribute. Checking against $(this).attr("class") is no good either because it could have multiple classes.
$(this).hasClass('p1') is faster.
Use .hasClass() to check the class.
$('p').on('click', function() {
if ($(this).hasClass('p1')) {
callThisFunction();
} else {
doNothing();
}
});
working demo : http://jsfiddle.net/nSMDA/
$('p').on('click', function() {
if ($(this).hasClass('p1')) {
console.log("do something");
} else {
console.log("do nothing");
}
});
Example:
http://jsfiddle.net/DNKUX/
If you need to differentiate behavior like this- where only some elements take action - what you should really be doing is only binding to the ones that match rather than to every <p> element.
$('p.p1').on('click', callThisFunction);
Here is a new fork of goma's jsfiddle: http://jsfiddle.net/4b8Pf/2/
if($(this).attr('class') === 'p1'){} is what you want to use. $(this).attr('class', 'p1') sets the current element to have a class of p1.
Related
I have several images with the same class and would like to set up a click function that changes the text in some elements based on which image is clicked.
My if statement is not working, I'm not entirely sure why because I've used this method before, or so I thought.
$('.gallery_image').click(function(e) {
var t = $(this);
if(t.id == 'csf') {
console.log('It works!');
}
});
JSFIDDLE
Use t.attr('id') instead of t.id
More about .attr()
An alternate solution is using classes instead of id's. Call the click function on the class they share then use a second class to distinguish them with the hasClass function:
<div id="csf" class="gallery_image csf">csf</div>
<div id="csi" class="gallery_image csi">csi</div>
$('.gallery_image').click(function(e) {
var t = $(this);
if(t.hasClass('csf')) {
alert("It works!");
}
else if(t.hasClass('csi')) {
alert("So does this!");
}
});
Is it possible to use the jquery attribute contains selector on $(this)? I cannot find any examples. I am trying to see if input fields contain a certain word.
$("#form input").keyup(function() {
if ($(this).filter( "[name~='someWord']" )) {
console.log('yes');
}
});
The code returns yes for all input even if they don't contain someWord.
You have to use .is() at this context,
if($(this).is( "[name~='someWord']" )) {
console.log('yes');
}
Because .filter() would return a jquery object (element collection), and that would never be false.
You can do this even better with Vanilla JS in the event handler
$("#form input").keyup(function(evt) {
if (evt.currentTarget.name.indexOf('someWord') > -1) {
console.log('yes');
}
});
This checks the name attribute of the actual DOM element and does not add the overhead of the jquery wrapper.
Try
$("#form input").keyup(function() {
if ($(this).filter("[name~='someWord']").length) {
console.log('yes');
}
});
or better:
$("#form input").keyup(function() {
if ($(this).is("[name~='someWord']")) {
console.log('yes');
}
});
I'm starting with jquery, and have an issue here:
http://jsfiddle.net/8guzD/
$('#test.off').click(function(){
$(this).removeClass('off').addClass('on');
});
$('#test.on').click(function(){
$(this).removeClass('on').addClass('off');
alert('ok');
});
the first part of the code goes well, the class is apply, but when I attach an event in this element with its new class it won't work.
Can someone explain me what is the problem exactly?
I tried with javascript,
http://jsfiddle.net/R5NRz/
var element = document.getElementById('test');
element.addEventListener('click', function() {
this.id ='test2';
alert("ok");
}, false);
var element2 = document.getElementById('test2');
element2.addEventListener('click', function() {
alert("ok2");
}, false);
and it didn't really help me, having the same issue
try
$(document).on("click",'#test.on',function(){
$(this).removeClass('off').addClass('on');
alert('ok');
});
$(document).on("click",'#test.off',function(){
$(this).removeClass('off').addClass('on');
alert('ok passs');
});
Demo
In your jQuery example you are binding to DOM elements that exist at that time. That is why you see the first fire but not the second. It is not a match for your '#test.on' selector when the code is run. What you want to do instead is use delegation:
$('#test').on('click',function() {
var ele = $(this);
if (ele.hasClass('on')) {
ele.removeClass('on').addClass('off');
} else {
ele.removeClass('off').addClass('on');
}
});
This assumes that you are doing more than just toggling classes. If you want simply toggle classes then an easier solution is to pick one as the default and use the other as a flag. For example, .on is on but without .on it's off. Then you can just use toggle:
$('#test').on('click', function() {
$(this).toggleClass('on');
});
$("#test.on")
Doesn't bind to anything. Try this:
$('#test').click(function() {
if($(this)).hasClass('off') $(this).removeClass('off').addClass('on');
else $(this).removeClass('on').addClass('off');
});
You might consider using an 'active' class instead and just toggling that, instead of have two separate on/off classes. Then you can write:
$("#test").click(function() {
$(this).toggleClass('active');
});
How would I select elements that have any ID? For example:
if ($(".parent a").hasId()) {
/* then do something here */
}
I, by no means, am a master at jQuery.
Like this:
var $aWithId = $('.parent a[id]');
Following OP's comment, test it like this:
if($aWithId.length) //or without using variable: if ($('.parent a[id]').length)
Will return all anchor tags inside elements with class parent which have an attribute ID specified
You can use jQuery's .is() function.
if ( $(".parent a").is("#idSelector") ) {
//Do stuff
}
It will return true if the parent anchor has #idSelector id.
You can do
document.getElementById(id) or
$(id).length > 0
You can using the following code:
if($(".parent a").attr('id')){
//do something
}
$(".parent a").each(function(i,e){
if($(e).attr('id')){
//do something and check
//if you want to break the each
//return false;
}
});
The same question is you can find here: how to check if div has id or not?
Number of .parent a elements that have an id attribute:
$('.parent a[id]').length
Simple way:
Fox example this is your html,
<div class='classname' id='your_id_name'>
</div>
Jquery code:
if($('.classname').prop('id')=='your_id_name')
{
//works your_id_name exist (true part)
}
else
{
//works your_id_name not exist (false part)
}
I seemed to have been able to solve it with:
if( $('your-selector-here').attr('id') === undefined){
console.log( 'has no ID' )
}
Pure js approach:
var elem = document.getElementsByClassName('parent');
alert(elem[0].hasAttribute('id'));
JsFiddle Demo
Simply use:
$(".parent a[id]");
You can do this:
if ($(".parent a[Id]").length > 0) {
/* then do something here */
}
You can use each() function to evalute all a tags and bind click to that specific element you clicked on. Then throw some logic with an if statement.
See fiddle here.
$('a').each(function() {
$(this).click(function() {
var el= $(this).attr('id');
if (el === 'notme') {
// do nothing or something else
} else {
$('p').toggle();
}
});
});
I have several divs that are alerts. The user dismisses them and after the final one (which is the FIRST in the DOM) I need to trigger some jquery magic.
Here's some simplified HTML:
<body>
<div class="">Bla bla bla</div>
<div class="alert">A</div>
<div class="alert">B</div>
</body>
Here's what I'm trying to do with jquery...
$(".alert").click( function() {
if ( $(this).is(".alert:first") ) {
//do stuff
}
});
It doesn't work. The conditional never returns true. The only way I can get it to work is using .index() but that sucks because if the order of the markup changes it will break the script.
What am I doing wrong?
EDIT: The solution uses .index() but in a way that I did not realize was possible. It is relative to the matched selection if used in that way. Thanks!
You can code:
$(".alert").click(function() {
if ($(".alert").index(this) == 0) {
//
}
});
http://jsfiddle.net/g2gGa/
Try this instead :
if ($(this).hasClass("alert") && $(this).is(":first")) {
//do stuff
}
Alternately :
$(".alert").click( function() {
if ($(".alert").index(this) == 0) {
//do stuff
}
});
Hope this will help !!
Try this jsfiddle
$(".alert").click( function() {
if (this == $(".alert:first")[0] ) {
//do stuff
alert(this);
}
});
you can try this.
$('.alert').click( function() {
if ( ($(this)[0] === $('.alert').first()[0])) {
alert('first');
}
});