I have the following example: http://jsfiddle.net/gespinha/yTjUL/13/
The variable should be triggered on click, making the link change class from on to off and change colour from red to green. But instead it starts already green, thus making the function useless.
Why does it not work?
HTML
<a id="link" href="javascript:void(0)" class="on">CLICK HERE</a>
JQUERY
$(document).ready(function () {
var $myVar = $(document).find('.on').addClass('off').removeClass('on');
$('link').click(function () {
$myVar
});
});
You seem to be under the impression that the variable will store a chain of actions to perform later, when the variable is 'called,' but that's not (clearly) what happens: the first line, within the ready() handler, in the var assignment, finds the .on element and performs the actions you specify, storing the .on element(s) in the variable (as jQuery methods almost all return the this object).
Instead:
$(document).ready(function () {
// use the `#link` notation, since 'link' is the id of the element:
$('#link').click(function () {
// assign a function to the click-event handler:
$('.on').addClass('off').removeClass('on');
});
});
Or, more simply (if you want to toggle between 'states') use toggleClass() and $(this) (rather than selecting from the whole of the document each time the user clicks the given element):
$(document).ready(function () {
$('#link').click(function () {
$(this).toggleClass('on off');
});
});
Also, rather than using javascript:void(0) in the href, simply use jQuery to prevent the default action, with:
$(document).ready(function () {
$('#link').click(function (e) {
e.preventDefault();
$(this).toggleClass('on off');
});
});
JS Fiddle demo.
References:
click().
event.preventDefault().
toggleClass().
It doesn't work that way, the variable will just contain the result of whatever methods you called, and for jQuery that means the element will be returned, so the variable $myVar only equals $(document) inside the event handler, it does not call the chained methods again.
You have to do:
$(document).ready(function () {
$('#link').on('click', function () {
$('.on').toggleClass('on off');
});
});
$(document).ready(function () {
$('#link').click(function () {
$(".on").addClass("off").removeClass("on");
});
});
As Guilherme Sehn noted, the $myVar variable is not needed. Just put your code in the click event. In addition, the link selector needs to be "#link", not "link".
By doing this, you'll be executing these actions and storing the return value (which will be the jQuery elements) inside $myVar. You can just put your code inside the click trigger function.
$('#link').click(function () {
$('.on').addClass('off').removeClass('on');
});
Also, you forgot the # before your ID. Without that your code will select link tags, not the element with the id link. And you do not need to explicity use $(document).find('.on') as all DOM elements are inside it.
I guess you meant $("#link")... and not $("link")
And if I understand right - the full script should be:
$(document).ready(function(){
$("#link").click(function(){
$(".on").addClass("off").removeClass("off");
});
});
You don't invoke the function and your selector is wrong.
$(document).ready(function () {
$('#link').click(function () {
$(document).find('.on').addClass('off').removeClass('on');
});
});
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 a set of images that are loaded via jQuery AJAX. For some reason, my click handler won't trigger when it is clicked.
JavaScript:
$(document).ready(function()
{
$('img.delete_related_sub').click(function()
{
alert('testing');
});
//I added this part to test, because the above wasn't working...
$(document).click(function(event)
{
alert(event.target.tagName+' '+event.target.className);
});
});
HTML:
<img data-rsid="2" class="delete_related_sub" src="image.png" />
So my 2nd click handler alerts me with "IMG delete_related_sub". But the first one isn't triggered. The is actually in a table that is actually in a pane run by bootstrap tabs, not sure if that'd actually help though.
Try it like this
$(document).on('click', 'img.delete_related_sub', function() {
alert('testing');
});
Just replace document with a static parent of your image.
Use this:
$("body").on('click', 'img.delete_related_sub', function() {
alert('testing');
});
Or, in the success: give this:
$('img.delete_related_sub').click(function() {
alert('testing');
});
Because the line to bind the event runs before the element is added, try using
$(parent).on('click', 'img.delete_related_sub', function() {});
where the parent is a static element that will be there for sure. This works because the event is bound to an element that actually exists, then checks to match your selector. See .on() for more details.
Something like
$(document).on('click', 'img.delete_related_sub', function() {});
would work fine.
$('.delete_related_sub').live("click", function()
{
alert('testing');
});
Use live event to listen clicks
I am modifying an ancient table which has inline JavaScript in the form of <a href="javascript:<lots of shit>">. The inline JavaScript works, but it would take months to rewrite it so that it fits my assignment, which is when an outer element is clicked the inline JavaScript should be executed.
I'm sorry if I'm not making any sense, but I have been as thoughtful as to provide a fiddle. (The table aspect shouldn't matter.) TL;DR: when I click one of the colored div's I would like its inner alert() to execute and how do I do that?
Edit. Also, the link is actually hidden!
Edit #2. And, as for now, none of the HTML should be tampered with. Only jQuery/JavaScript.
Edit #3. I've updated the script to work with my table. The inner <span> is now not needed, I can select the <a> directly. Now I would just like to know if I'm using stopPropagation() correctly?
Code:
$(function () {
$('table.result-v2 tr.view').bind('click', function () {
var $this = $(this),
$next = $this.next();
if ($next.attr('class') == 'detail') {
var $buttons = $this.find('td.buttons'),
$link = null;
if ($next.css('display') == 'none') {
$link = $buttons.find('a.show-link');
} else {
$link = $buttons.find('a.hide-link');
}
if ($link != null) {
eval($link.attr('href')); // evaluate found link
$link.bind('click', function (event) {
event.stopPropagation(); // is this needed when the link never can be clicked (it's hidden)?
});
}
}
});
});
Here is a quick hack that made your code work. And just to note that this is totally not how it should be done!
http://jsfiddle.net/2QaUX/1/
Instead of triggering a click, evaluate the inline script inside the href attribute:
Old:
$(function () {
$('.foo').bind('click', function () {
$(this).find('.bar').parent().trigger('click');
});
});
New:
$(function () {
$('.foo').bind('click', function () {
eval($(this).find('.bar').parent().attr('href'));
});
$('.bar').parent().bind('click', function (event) {
event.stopPropagation();
});
});
just place that js whithin a function
function clikEvent(ele)
{
//<lots of shit>
}
and call it on onclick and replace href js with void like
<a href="javascript:void(0)" onClick='clikEvent(this)'>
you have to also tack care of the data passed I have placed parameter ele wich will point the href so you can retrive id of or any other thing
if you want to use jQuery
$('#idofAtag').click(function(){//<lots of shit>});
There are two issues here. One is event propagation. When you click the div, you trigger a click on the link, which is also a click on the div. This creates an infinite loop which will quickly exceed the maximum call stack size. To get around this, you need to do two things:
Only execute the window.location.href assignment if the user clicked on the div and not the a within it.
If the user DOES click on the a, prevent the event from bubbling up to the div
The second issue is that the 'click' event on a link won't execute javascript stored in an href attribute. what you want to do is set window.location.href.
$('.foo').on('click', function (e) {
var link = $(this).find('.bar').parent('a');
if(e.target != link.get(0)) {
window.location.href = link.attr('href');
}
});
$('.foo').on('click', 'a', function(e) {
e.stopPropagation();
});
Here's a demo
--- jsFiddle DEMO ---
- NOTE - I would strongly recommend finding another way to handle this situation, but if you cannot alter the existing links, this option is viable.
I have a click handler that reads the href attribute of an a tag and loads the new content via ajax. The function returns false so it doesn't follow the href url. This works once, but each time thereafter, the function does not appear to get called and the content is not loaded asynchronously, but instead follows the link in the browser.
$ ("document").ready( function () {
$(".post_update").click( function () {
$("#dashboard_content").html(ajax_load).load($(this).attr('href'));
return false;
});
});
Edit
you should not use document as a string its an object itself try the belwo code.
Since the link is inside dashboard container you should use live in this case.
$(document).ready( function () {
$("a.post_update").live('click', function () {
$("#dashboard_content").html(ajax_load).load($(this).attr('href'));
return false;
});
});
If .post_update is inside #dashboard_content, the problem is that the element to which the event handler was bound, is now gone. The simplest solution, is to use the jQuery.live method. So your code would look like:
$(document).ready(function () {
$(".post_update").live("click", function (e) {
$("#dashboard_content").html(ajax_load).load($(this).attr('href'));
return false;
});
});
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
});