Is it possible to add a onclick event to any button by jquery or something like we add class?
function onload()
{
//add a something() function to button by id
}
Calling your function something binding the click event on the element with a ID
$('#id').click(function(e) {
something();
});
$('#id').click(something);
$('#id').bind("click", function(e) { something(); });
Live has a slightly difference, it will bind the event for any elements added, but since you are using the ID it probably wont happen, unless you remove the element from the DOM and add back later on (with the same ID).
$('#id').live("click", function(e) { something(); });
Not sure if this one works in any case, it adds the attribute onclick on your element: (I never use it)
$('#id').attr("onclick", "something()");
Documentation
Click
Bind
Live
Attr
Yes. You could write it like this:
$(document).ready(function() {
$(".button").click(function(){
// do something when clicked
});
});
$('#id').click(function() {
// do stuff
});
Yes. Something like the following should work.
$('#button_id').click(function() {
// do stuff
});
Related
I've tried to simplify it, simple enough to make my question clearer.
The alert 'I am a boy' didn't popup with even after the addClass has been executed.
Here is my code:
$(".first").click(function () {
var a = $(this).html();
if (a=='On') {
$(this).removeClass('first').unbind().addClass('second');
$(this).html('Off');
}
});
$(".second").click(function () {
alert('I am a boy');
});
<button class="first">On</button>
This behavior is because you are apply a class to an element after the DOM has loaded, in other words dynamically. Because of this, your event listener attached to the control for '.second' isn't aware of the newly added class and doesn't fire when you click on that control.
To fix this, you simply need to apply your event listener to a parent DOM object, typically $(document) or $('body'), this will ensure it is aware of any children with dynamically added classes.
As George Bailey said, you can refer here for a in depth explanation.
In regards to your specific code, the fix is to simply adjust it as so:
$(".first").click(function () {
var a = $(this).html();
if (a=='On') {
$(this).removeClass('first').unbind().addClass('second');
$(this).html('Off');
}
});
/* Changed this:
$(".second").click(function () {
alert('I am a boy');
});
*/
// To this:
$(document).on('click', '.second', function () {
console.log('I am a boy');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="first">On</button>
The function you pass to $.post doesn’t run until later (a callback). So the class is added after you try to select it. Do it inside the callback, the same way you added the class (and you don’t need to select that class, just use $this)
I have the following code:
$('#button-a').click(function(){
$('#button-b').click(function(){
alert('something');
});
});
$('#button-b').click(function(){
// do something
});
How can I deactivate the nested #button-b function after I have clicked #button-a, so only the last #button-b function (not nested) activates when i click #button-b and not them both?
Try this using .on() and .off() event handlers.
$('#button-a').click(function(){
$('#button-b').off('click'); //unbind the click event of the #button-b
$('#button-b').click(function(){
alert('something');
});
});
$('#button-b').on('click',function(){
// do something
});
In order to accomplish this, your function cannot be anonymous. You need to use the form of off which specifies the handler to remove. Rewriting your code a bit, it'd look something like this:
function myFunc() {
alert('something');
}
$("#button-a").click(function() {
$("#button-b").click(myFunc);
});
$("#button-b").click(function() {
// do something
});
To remove the handler, you'd use:
$("#button-b").off('click', myFunc);
I'm not quite sure where you want this to occur, but the above line of code will work anywhere that the DOM has been loaded and myFunc is in scope.
If you feel you definitely need an anonymous handler here, you can use event namespace for your task - http://api.jquery.com/on/
$('#button-b').on('click.nestedClick', function(){
alert('something');
});
// and unbind it at some point:
$('#button-b').off('click.nestedClick');
$('#button-a').click(function(){
$('#button-b').trigger('click');
});
$('#button-b').click(function(){
// do something
});
Change your code like this so it call your last function for button-b when you click on button-a
So I'm going to explain this with an example.
I have a "like" button (class: .like) for my feed or stream. When the user clicks it ( using $(".like") ), it ajaxes it's way to refreshless insert the like into the database (using jQuery).
When it's inserted, I change the text to "Unlike" and the class to ".unlike".
However, when a user reclicks it, it just goes through the same function again, instead of going to the $(".unline").click function. Do I have to "update" the script or something?
For example:
$(".like").click(function(){
alert("Like!");
$(this).attr("class", "unlike");
});
$(".unlike").click(function(){
alert("Unlike!");
$(this).attr("class", "like");
});
The problem is that it won't to the unlike function, it will just repeat the like function even though the attribute is changed.
That is because the "unlike" attr. hasn't been added to the dom when the script loaded. Try this:
<body>
<div class="like_it_or_not">
HELLO!
</div>
</body>
And the JS
$("body").on('click','.like_it_or_not', function(){
$(this).toggleClass('like', 'unlike');
if ($(this).hasClass('like')) {
alert('like');
} else if ($(this).hasClass('unlike')) {
alert('unlike');
}
});
If you don’t want to delegate your click event (which is over-engineering IMO), do a check in the handler:
$(".like").click(function(){
alert( $(this).hasClass('unlike') ? 'unlike' : 'like' );
$(this).toggleClass("unlike like");
});
http://jsfiddle.net/NScyM/
It should check for the 'unlike' class each time you click and toggle classes as expected.
The event binding occurs when you assign run the above code. You have to rebind the event every time, or, better yet, use event delegation:
$(document)on("click",".like",function(){
alert("Like!");
$(this).addClass("unlike");
$(this).removeClass("like");
});
$(document)on("click",".unlike",function(){
alert("Unike!");
$(this).addClass("like");
$(this).removeClass("unlike");
});
I think you will have to use live() or on() to make this work:
$(".like").live("click", function() {
$(this).removeClass("like").addClass("unlike");
});
$(".unlike").live("click", function() {
$(this).removeClass("unlike").addClass("like");
});
Try this one
$(".like").click(function(){
alert("Like!");
$(this).removeClass("like");
$(this).attr("class", "unlike");
});
$(".unlike").click(function(){
alert("Unlike!");
$(this).removeClass("unlike");
$(this).attr("class", "like");
});
To keep my code clean on stuff like this, I assign a class that never changes and tie the click event to that. The styling classes simply act as CSS changes. For instance:
<button class="vote like">button text</button>
$('.vote').click(function () {
var alertText = ($(this).hasClass('like')) ? 'Like!' : 'Unlike!';
alert(alertText);
$(this).toggleClass('like').toggleClass('unlike');
});
Try this
$(document).on('click', '.like', function(){
alert("Like!");
$(this).html('Unlike').removeClass("like").addClass("unlike");
});
$(document).on('click', '.unlike', function(){
alert("Unlike!");
$(this).html('Like').removeClass("unlike").addClass("like");
});
DEMO.
The unlike click event handler has not been associated with the new item. If you're going to be changing the class dynamically like that you're going to want to look at the (jQuery on handler)[http://api.jquery.com/on/]
$(document).on('click',".like", function(){
alert("Like!");
$(this).addClass("unlike").removeClass('like');
});
$(document).on('click',".unlike",function(){
alert("Unlike!");
$(this).addClass("like").removeClass('unlike');
});
I am waiting for the document.ready event in order to do something on my page.
Alas some other script, which I cannot change, has not worked its magic yet once my script is called. Hence, jquery selection on the class name fails as the class does not yet exist in the DOM.
This is why I want tell my function to listen until an element gets a certain class, then do something with it.
How do I achieve this?
Something like this (pseudo code) :
var timer = setInterval(function() {
if (element.className=='someclass') {
//run some other function
goDoMyStuff();
clearInterval(timer);
}
}, 200);
or listen for the element to be inserted:
function flagInsertedElement(event) {
var el=event.target;
}
document.addEventListener('DOMNodeInserted', flagInsertedElement, false);
jQuery version:
$(document).on('DOMNodeInserted', function(e) {
if (e.target.className=='someclass') {
goDoMyStuff();
}
});
There's also the liveQuery plugin:
$("#future_element").livequery(function(){
//element created
});
Or if this is a regular event handler, delegated events with jQuery's on();
You could trigger some event once you added the class.
Example:
$('#ele').addClass('theClass');
$(document).trigger('classGiven')
$(document).bind('classGiven',function(){
//do what you need
});
I'm sorry if I got your question wrong but why not just doing something plain as this on document.ready ? :
$("#myelement").addClass('myclass');
if($("#myelement").hasClass('myclass')) {
alert('do stuff here');
}
I have an element, a div, for example. And attach an event 'click' to it. In jQuery, it would be:
$('#myDiv').click(function(){
$(".class1").show();
})
Now, I would like to assign a new function "myDiv #", replacing the old. I am doing so:
$('#myDiv').click(function(){
$(".class23").hide();
})
But when I run the 'click' on the div, the function I assigns the beginning of this doubt is performed.
Question: How to remove the function that will run with the click event attributed to an element? (No recreate the element with the new click event...)
You want .unbind.
You can either remove all previous bound functions:
$('#myDiv').unbind('click');
Or if you only want to unbind one specific function:
var show = function() {
$(".class1").show();
};
$('#myDiv').click(show);
and then:
$('#myDiv').unbind('click', show); // unbind first function
$('#myDiv').click(function() { // bind second function
$(".class23").hide();
});
Note that .click(func) is just a shortcut to .bind('click', func).
If you know you'll only want to handle one click on an element, you can use one() which automatically unbinds after a single click:
$("#myDiv").one("click", function() {
$(".class1").show();
$("#myDiv").one("click", function(){
$(".class23").hide();
});
});
Use the JQuery unbind function to remove all click events
$('#myDiv').unbind('click');
Add a counter on the first click event.
var counter = 0;
$('#myDiv').click(function(){
if(counter>1){
$(".class23").hide();
}
else
$(".class1").show();
counter++;
})
just an example..