Access an element by class using jQuery - javascript

I have a table with an ID of InstrumentListGrid. When a row is selected, it sets the class to ui-iggrid-activerow. I want to add a jQuery event on that row for when someone clicks it.
So far I have
$("#InstrumentListGrid tr.ui-iggrid-activerow").click(function (event) {
alert("YAY!");
});
but that isn't firing. How do I bind to an element by class?

since the class is presumably added dynamically you should use .delegate()
$('#InstrumentListGrid').delegate('.ui-iggrid-activerow', 'click', function (e) {
// do stuff.
});

It appears that ui-iggrid-activerow is dynamically added. Use the live() function:
$('#InstrumentListGrid tr.ui-iggrid-activerow').live('click', function() {
alert('YAY!');
});

Related

Jquery replaceWith() inside loop with click events

im trying to replace various elements with another inside a jquery .each loop and give them on click events to their child nodes, but it does not work, here is my code.
var replacer = function () {
var elementbody = "<div class='Container'><div class='Button'></div></div>";
$('.myclass').each(function (index, element) {
$(element).replaceWith(elementBody);
$(element).find('.Button').click(function () {
//------------------To do on click event------------------//
});
};
After you use
$(element).replaceWith(...);
element still refers to the old element, not the elements that have replaced it. So $(element).find('.Button') doesn't find the button you just added.
Instead of adding the handler to each element that you add, use delegation to bind a handler just once, as explained in Event binding on dynamically created elements?
$("someSelector").on("click", ".Button", function() {
...
});
You can use a delegate as Barmar suggests or you could provide yourself with a new jquery object that references your new content before running the replaceWith
Something like this, maybe:
new_element = $('<div><button>Hello World</button></div');
$(element).replaceWith(new_element);
new_element.find('button').on('click', function(e) {
console.log(e);
});

jQuery delete trigger conditionally

I was wondering if Javascript or jQuery have a way to delete an event listener. Let's say I want to make a function that I want to trigger only once, for example let's say I want to have a button that shows some hidden elements on the document, I would make this function (assuming the hidden elements have a hidden class that hides them):
jQuery('#toggler').click(function() {
console.log('Hidden elements are now shown');
jQuery('.hidden').removeClass('hidden');
});
Simple enough, right ? Now, my actual problem comes in, I don't want jquery to run that function again and again each time the button is clicked, because the elements are already revealed, so is there a clean way to do it ? So, in this example after clicking the toggler multiple times I want to get only one console message.
I could do jQuery(this).unbind('click'), but this results into removing ALL triggers and I only want to remove the current trigger.
What I usually do when I face such scenarios is solve it like this (which is ugly and doesn't actually prevent code execution, but only handles the code's results) :
var toggler_clicked = false;
jQuery('#toggler').click(function() {
if(toggler_clicked) return;
toggler_clicked = true;
console.log('Hidden elements are now shown');
jQuery('.hidden').removeClass('hidden');
});
Also I don't want to use jQuery's one, because I will have the same problem when I'll need to delete the trigger conditionally, so if you can help please give me a dynamic answer.
Thanks in advance !
You have to name your function like that:
var myFunction = function() {
console.log('Hidden elements are now shown');
jQuery('.hidden').removeClass('hidden');
};
And bind it this way
jQuery('#toggler').click(myFunction);
Then you can unbind it with :
jQuery('#toggler').off('click',myFunction);
Without unbinding the other listeners
You can try this:
var myFunc = function() {
console.log('Hidden elements are now shown');
jQuery('.hidden').removeClass('hidden');
jQuery(this).unbind('click', myFunc);
};
jQuery('#toggler').click(myFunc);
This way of calling unbind is such that only the listener for myFunc handler is removed and not all the events connected to the click on the toggler.
I would use the .on() and its opposite .off() methods to attach/detach the event handler. It is the recommended way since 1.7 instead of the .bind() and .unbind() versions that became deprecated as of jQuery 3.0.
$("#toggler").on("click", function(event) {
console.log('Hidden elements are now shown');
$('.hidden').removeClass('hidden');
// if (/* Add your condition here */) {
$(this).off(event);
// }
});
$("#toggler").on("click", function(event) {
console.log('Hidden elements are now shown');
$('.hidden').removeClass('hidden');
// if (/* Add your condition here */) {
$(this).off(event);
// }
});
.hidden {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="toggler">Toggle</button>
<div class="hidden">
HIDDEN
</div>
Try this
var myFunction = function() {
console.log('Hidden elements are now shown');
jQuery('.hidden').removeClass('hidden');
};
Add the event listener like this:
jQuery('#toggler').addEventListener("click", myFunction);
And remove it like this:
jQuery('#toggler').removeEventListener("click", myFunction);
So all together this will do the trick:
var myFunction = function() {
console.log('Hidden elements are now shown');
jQuery('.hidden').removeClass('hidden');
jQuery('#toggler').removeEventListener("click", myFunction);
};
jQuery('#toggler').addEventListener("click", myFunction);
more about the HTML DOM removeEventListener() Method
Jquery unbind function takes 2 parameters eventType and handler
You can put your event listener into separate function like this:
var clickEventHandler = function(){
//your logic goes here
}
After you add listener as reference:
jQuery('#toggler').click(clickEventHandler);
And then, later, anytime, anywhere you want you can unbind that specific handler:
jQuery('#toggler').unbind('click', clickEventHandler);
What i used to do in the past is toggle the click behavior using css classes, ex i used to set a click listener on the parent and delegate to all of the children something that jquery is doing now by default i believe. Anyway based on the css class it will trigger an event for ex.
$('.some-parent-element').on(
'click',
'the-behavior-css-class',
function() { // do stuff here.... }
)
Now if you want to remove this behavior you can just toggle the class of the element and it should do the job. ex
$('.some-parent-element').on(
'click',
'hide-me-on-click-or-whatever',
function() {
$(this).toggleClass('hide-me-on-click-or-whatever')
// perform the action
}
)
You can check if the element has the class hidden

Click event on dynamic elements not working

In framework7, how to add click event on dynamic elements?
If I add my element first on my view, the click event works fine like below:
<div class="test">Click Me</div>
$$('.test').on('click', function () {
myApp.alert("Gotcha!");
});
But if I have dynamic elements, especially elements dynamically added to virtual-list, I cannot make the click event to work. What is the right way to do this?
I even tried inline function, ex: <div class="test" onclick="myFunction();">Click Me</div>, still this won't work.
You can use:
// Live/delegated event handler
$$(document).on('click', 'a', function (e) {
console.log('link clicked');
});
For your case:
$$(document).on('click', '.test', function(e){
console.log('Some code...');
});
Here is docs. Scroll until events section.
Use this for dinamically added elements:
$$(document).on('click', '.test', function () {
myApp.alert("Gotcha!");
});
All answers are good to go with. But if you are using this class 'test' for other elements of the page, you will end up firing some extra click event(when you click on any other element of same class). So if you wanna prevent that, you should add listener to that particular element.
if you're adding an element of class test to an existing element of id testId, then use
$('#testId').on('click', '.test', function(this){
}
In the function where you dynamically add the new elements you have to assign an event handler for them.
Lets say you have a function something like this
function addNewLines(){
//add the new lines here
// you have to run this again
$$('.test').on('click', function () {
myApp.alert("Gotcha!");
});
}

jQuery click function acting strange when adding/removing classes

I have two list items that, when clicked, should change classes from '.off' to '.on'. Only one element should be '.on' at a time so when one is already turned on and the other is clicked both elements should change classes from '.off' to '.on' and vice versa. If a list item with a class of '.on' is clicked it should change classes to '.off'
The problem I am having is when a list item with class '.on' is clicked it still runs the click function as if it had a class of '.off'
My html:
<ul>
<li>ABOUT</li>
<li>SUBMIT</li>
</ul>
My javascript (running on jQuery 1.7.1)
$('.off').click(function(event) {
event.preventDefault();
$(".on").addClass("off").removeClass("on");
$(this).addClass("on").removeClass("off");
});
$('.on').click(function(event) {
event.preventDefault();
$(this).addClass("off").removeClass("on");
});
Does anyone know what is going on here? Is there something wrong in my code or have I encountered some sort of bug here?
http://jsfiddle.net/ZC3CW/6/
The selectors you're using to bind the event using click() are used to select the elements to add the event handler to. The selector is not considered when the handler is run.
You should be looking for something more like this:
$('li').click(function(event) {
event.preventDefault();
if ($(this).hasClass('off')) {
$(".on").addClass("off").removeClass("on");
$(this).addClass("on").removeClass("off");
} else { // $(this).hasClass('on');
$(this).addClass("off").removeClass("on");
}
});
You might want to make the li selector more explicit by adding a class/id to the ul or li's.
To confuse things further, you could also do this (if you're using jQuery > 1.7);
$(document).on('click', '.off', function(event) {
event.preventDefault();
$(".on").addClass("off").removeClass("on");
$(this).addClass("on").removeClass("off");
});
$(document).on('click', '.on', function(event) {
event.preventDefault();
$(this).addClass("off").removeClass("on");
});
This is because the .on() function works by attaching the event handler to the selected elements (document), and will only execute the handler (the function) on the event specified (click) if the element that the event originated from matches the selector .off at the time the event fired, not at binding time.
I would suggest adding a click handle to a different selector, this should work for you...
$("ul li a").click(function(e){
e.preventDefault();
if($(this).hasClass("off")){
$("ul li a").addClass("off").removeClass("on");
$(this).addClass("on").removeClass("off");
}
else{
$(this).addClass("off").removeClass("on");
}
});
The problem is that jQuery handlers get attached at page load and remain the same regardless of changing their classes. Use live('click', handler) on('click', handler) instead of click().
Edit: just noticed that .live() is deprecated in jQuery 1.7.
The problem as I see it is that your "on" class is not in play at the time of the click event, so your $('.on').click method is never being called.
Try re-assigning your events after changing classes (example follows) :
var assignClicks = function () {
$('.off').click(function(event) {
event.preventDefault();
$(".on").addClass("off").removeClass("on");
$(this).addClass("on").removeClass("off");
assignClicks();
});
$('.on').click(function(event) {
event.preventDefault();
$(this).addClass("off").removeClass("on");
assignClicks();
});
};
assignClicks();
Hope this helps,
Pete
The click is bound to the element not the class.
Maybe you can attach the events to the elements and detect/toggle the elements classes:
$('li').click(function(event) {
event.preventDefault();
if( $(this).hasClass('on') ) {
$(this).removeClass('on');
}
else {
$(this).addClass('on');
$(this).siblings().removeClass('on');
}
});

jQuery Issue: functions won't work on newly created HTML element

I have two functions: one that creates a new <textarea> when a button is clicked, and a second function that performs an action when the <textarea> is clicked (or blurred, changed, etc.) That second function selects elements based on a class name. It seems that the second function only works on those matching elements that existed when the page was loaded, but it will not activate on any newly created <textarea> elements. Can anyone figure out why and how to fix this? You'll find the code below. Thanks. --Jake
$('#add').click(function() {
$(this).before("<textarea class='test'></textarea>")
})
$('.test').blur(function () {
alert('just a test')
})
The textarea you create isn't around at the time jQuery assigns the action to elements tagged with the .test class. You'll need the live() function to make this work as desired.
$('.test').live('blur', function () {
alert('just a test')
});
Now any element tagged with .test will automatically bind the specified function on blur no matter when it's created.
You can bind it directly:
$('#add').click(function() {
$(this).before("<textarea class='test'></textarea>").prev().blur(function () {
alert('just a test');
});
});
Or place use jQuery's .delegate() method to place a handler on the parent of #add.
$('#add').click(function() {
$(this).before("<textarea class='test'></textarea>")
}).parent().delegate('.test','blur',function() {
alert('just a test');
});
This is a more efficient approach than using .live().

Categories