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');
});
Related
I have following code:
$(document).bind('click', '.btn-yes .btn-no', function() {
$(this).toggleClass("btn-warning");
alert("test"); // <-- this works...
});
.btn-yes and .btn-no are two classes which are attached to buttons. When they are clicked, I want the btn-warning class to get attached to that button, but this is not working...
Can anyone let me know what I am doing wrong?
You need to have a comma , between your selector:
'.btn-yes, .btn-no'
and you should use event delegation only if your elements are dynamically generated after page load.
If such a case then the preferred method is .on() as per latest jQuery library. You can see this in action in the snippet below.
$(document).on('click', '.btn-yes, .btn-no', function() {
$(this).toggleClass('btn-warning');
});
.btn-warning{background:red; color:yellow;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class='btn-yes'>Yes</button><button class='btn-no'>No</button>
Problem:
When you don't use comma , in your selector such as in this case you are actually trying to bind a click event on the child .btn-no which has the parent .btn-yes.
Try this:
$(document).bind('click','.btn-yes .btn-no',function(e){
$(e.target).toggleClass("btn-warning");
});
'.btn-yes .btn-no' denotes to the btn-no inside btn-yes not separate elements. So, separate your elements with a comma and use click event for that.
I also recommend you to use on instead of bind method:
$(document).on('click', '.btn-yes, .btn-no', function(){
$(this).toggleClass("btn-warning");
});
If you have jquery version 1.7+ use on method
$(document).on('click', '.btn-yes,.btn-no', function() {
$(this).toggleClass("btn-warning");
});
This is my code :
<html>
<body>
<button class="myclass" data-card-id="1">Save</button>
</body>
</html>
My question is how whould look like a function that when user click on any of "myclass" buttons submit a variable with data-card-id of the specific card in a php file.
Thank you ! :)
this is using Jquery:
$(".myclass").click(function(){
$(this).attr( "data-card-id" );
});
JSFIDDLE - http://jsfiddle.net/q5j8z/11/
see browser console for data display
// change the selector "ul li a" to your button
$('ul li a').click(function (e) {
e.preventDefault();
var value = $(this).data('value');
$('.button').data('value', value);
console.log($('.button').data('value'));
});
$('.button').click(function (e) {
e.preventDefault();
console.log($(this).data('value'));
});
This can be accomplished through an additional selection feature. I believe "data-card-id" is an attribute of your html tag, so you have two choices.
Bind the click to the element using the selector or delegate it to the body of the document, I think you'll see how either way works here.
Option 1. The advantage here is that when click events bubble up to the body this will check and execut appropriately, even if other buttons are added to the page after this code is executed. This is jquery's click delegation feature
$('body').on('click', 'button[data-card-id="1"]', function(){
//perform your action
});
Option 2. This binds the click event to the object itself. This can be more straight forward and has its advantage in simplicity.
$('button[data-card-id="1"]').click(function(){
// perform some action
});
And of course you have a plethora of other approoaches......
or
$('button').each(function(){
if($(this).attr("data-card-id") == '1'){
$(this).click(function(){
//some action
});
}
});
There are other approaches, too. Let me know if none of these seem to work.
JS FIDDLE DEMO
The most simpler would be to use this code -- >
just change this card-id to this cardid
HTML
<button class="myclass" data-cardid="1">Save</button>
<button class="myclass" data-cardid="2">Save</button>
JS
$(document).ready(function(){
$(".myclass").on('click',function(){
var cid = $(this).data("cardid");
alert(cid);
});
});
I understand that you need to use ".on" to use code that you loaded with jquery after the page has loaded. (At least I think it works that way)
So I tried that but it somehow just doesn't do a thing at all. No errors in the console either.
$("#forgot_password").click(function(){
var forgot_password = '<div id="toLogin" style="cursor:pointer;">Prijava</div>'
$("#loginPopupForm").html(forgot_password);
});
$("#toLogin").on("click", function(){
alert("Hello");
});
So when I click on #forgot_password it does execute the first click function. But when I click on #toLogin it doesn't do anything and I think its because its loaded with jquery when I click on #forgot_password
Try this
$("#loginPopupForm").on("click", "#toLogin", function(){
alert("Hello");
});
You need to bind to an element that is present when the page loads, like body for example. Just change your code to what is shown below
$("body").on("click", "#forgot_password", function(){
var forgot_password = '<div id="toLogin" style="cursor:pointer;">Prijava</div>'
$("#loginPopupForm").html(forgot_password);
});
$("body").on("click", "#toLogin", function(){
alert("Hello");
});
You are setting the on to the wrong thing. You want it to be:
$(document).on('click', '#toLogin', function() {alert('hello') });
The id isn't there until you do the other click event, so jQuery is not finding any element to set the click event on. You need to have an element that has been rendered in the DOM to set the event on.
You are totally right about the problem : on() targets only elements that are already existing as it runs.
What you need in jQuery is called Delegated event and is well explained on the Jquery doc page.
The difference in the code is thin, but it's how you're supposed to do.
You have to specify the parent element
$("#toLogin").on("click","#loginPopupForm", function(){
alert("Hello");
});
in the 2nd argument of the on
I'm trying to manipulate an id to use the same button to do more then 2 actions.
its something like:
var id;
if(something == 2){
id = "id";
}else{
id = "id2";
}
$(".myClass").attr("id", id);
but, its not good, because if i try to use the id that i set, won't work, maybe because the document was already loaded with no id in the button.
dont think this need a example, but i made it.
have another way to do this ?
If you need to bind actions to some future element, it's generally best to use delegation, meaning to listen for the events not on the elements themselves, but on one of their ancestors:
$("body").on("click", "#id2", function(){
alert( "Clicked!" );
});
At this point, you can set the ID dynamically:
$(".myClass").attr("id", function(){
return something === 2
? "id"
: "id2" ;
});
While I am listening for the click event on the body, it's generally best to use a closer parent element so the event doesn't have to bubble too much before being handled.
Use this:
$(document).on('click', '#alertMe', function(){
alert('Working');
});
Try like this
$("#alertMe").live("click",function(){
alert('Working');
});
Don't use 'click()' to bind the handler, use live:
$("#alertMe").live('click', function(){
alert('Working');
});
The reason is that the click method is a one time deal. It adds the click event to that id at the point it runs. To dynamically handle click event on that id use on like this:
$(".button1").click(function(){
$(".button2").attr("id", "alertMe");
});
$(document).on('click',"#alertMe", function(){
alert('Working');
});
Live example: http://jsfiddle.net/SWZMd/17/
You can also set the click after you set the id:
$(".button1").click(function(){
$(".button2").attr("id", "alertMe");
$("#alertMe").click(function(){
alert('Working');
});
});
Move second click event into the first click event, then it will work.
$(".button1").click(function(){
$(".button2").attr("id", "alertMe");
$("#alertMe").click(function(){
alert('Working');
});
});
http://jsfiddle.net/dcai/SWZMd/18/
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
});