I am trying to make some text that changes when you click it, but changes back if you click it again.
It works fine, once. But if i try it a second time, nothing happens.
My HTML:
<div id="text">
<p>TEXT1</p>
</div>
JavaScript/jQuery:
$(document).ready(function(){
$("#text").click(function(){
$(this).html("<p>TEXT2</p>").click(function(){
$(this).html("<p>TEXT1</p>");
});
return false;
});
});
Example:
http://mrkireko.github.io/jQueryExample/
I'd suggest instead:
$('#text p').click(function(){
$(this).text(function(i,t){
return $.trim(t) === 'text1' ? 'text2' : 'text1';
});
});
JS Fiddle demo.
References:
click().
jQuery.trim().
text().
It's because after the first click, you now have two handlers assigned,
The first one still puts the TEXT2 in place, but the second one changes it back.
One correct solution is to use the handler version of .toggle():
$(document).ready(function(){
$("#text").toggle(function(){
$(this).html("<p>TEXT2</p>");
return false;
}, function(){
$(this).html("<p>TEXT1</p>");
return false;
});
});
As #KevinB noted, this version of .toggle() is deprecated. To do your own toggle, you can do this:
$(document).ready(function() {
$("#text").click(function(i){
return function() {
$(this).html(++i % 2 ? "<p>TEXT2</p>" : "<p>TEXT1</p>");
return false;
};
}(0));
});
DEMO: http://jsfiddle.net/NkGZj/
You are binding multiple click handlers to the same element, and they are all executing every time you click. Since the handler to change the text to TEXT1 executes last, that's what you end up with.
See the console.log() output here:
http://jsfiddle.net/tcMx5/
Binding event handlers in event handlers is almost never the right thing to do. Instead, have one handler that checks the current state and toggles the value.
Several answers here, some will work well. Here is another option, using class:
<div id="text" class="state1">
<p>TEXT1</p>
</div>
$(document).ready(function(){
$("#text").click(function(){
var $this = $(this);
if ($this.hasClass('state1')) {
$this.html('<p>TEXT2</p>');
}
else {
$this.html('<p>TEXT1</p>');
}
$this.toggleClass('state1');
});
});
I would lean more towards this solution because it is not dependent on what is actually contained within the element. Unless, of course, you know that it will never change and you can reliably target the string.
You can do something like this:
$( "#text" ).toggle(function() {
this.html("<p>text 2</p>");
}, function() {
this.html("<p>text 1</p>");
});
Related
I'm having a hard time understand how to simulate a mouse click using JQuery. Can someone please inform me as to what i'm doing wrong.
HTML:
<a id="bar" href="http://stackoverflow.com" target="_blank">Don't click me!</a>
<span id="foo">Click me!</span>
jQuery:
jQuery('#foo').on('click', function(){
jQuery('#bar').trigger('click');
});
Demo: FIDDLE
when I click on button #foo I want to simulate a click on #bar however when I attempt this, nothing happens. I also tried jQuery(document).ready(function(){...}) but without success.
You need to use jQuery('#bar')[0].click(); to simulate a mouse click on the actual DOM element (not the jQuery object), instead of using the .trigger() jQuery method.
Note: DOM Level 2 .click() doesn't work on some elements in Safari. You will need to use a workaround.
http://api.jquery.com/click/
You just need to put a small timeout event before doing .click()
like this :
setTimeout(function(){ $('#btn').click()}, 100);
This is JQuery behavior. I'm not sure why it works this way, it only triggers the onClick function on the link.
Try:
jQuery(document).ready(function() {
jQuery('#foo').on('click', function() {
jQuery('#bar')[0].click();
});
});
See my demo: http://jsfiddle.net/8AVau/1/
jQuery(document).ready(function(){
jQuery('#foo').on('click', function(){
jQuery('#bar').simulateClick('click');
});
});
jQuery.fn.simulateClick = function() {
return this.each(function() {
if('createEvent' in document) {
var doc = this.ownerDocument,
evt = doc.createEvent('MouseEvents');
evt.initMouseEvent('click', true, true, doc.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
this.dispatchEvent(evt);
} else {
this.click(); // IE Boss!
}
});
}
May be useful:
The code that calls the Trigger should go after the event is called.
For example, I have some code that I want to be executed when #expense_tickets value is changed, and also, when page is reload
$(function() {
$("#expense_tickets").change(function() {
// code that I want to be executed when #expense_tickets value is changed, and also, when page is reload
});
// now we trigger the change event
$("#expense_tickets").trigger("change");
})
jQuery's .trigger('click'); will only cause an event to trigger on this event, it will not trigger the default browser action as well.
You can simulate the same functionality with the following JavaScript:
jQuery('#foo').on('click', function(){
var bar = jQuery('#bar');
var href = bar.attr('href');
if(bar.attr("target") === "_blank")
{
window.open(href);
}else{
window.location = href;
}
});
Try this that works for me:
$('#bar').mousedown();
Technically not an answer to this, but a good use of the accepted answer (https://stackoverflow.com/a/20928975/82028) to create next and prev buttons for the tabs on jQuery ACF fields:
$('.next').click(function () {
$('#primary li.active').next().find('.acf-tab-button')[0].click();
});
$('.prev').click(function () {
$('#primary li.active').prev().find('.acf-tab-button')[0].click();
});
I have tried top two answers, it doesn't worked for me until I removed "display:none" from my file input elements.
Then I reverted back to .trigger() it also worked at safari for windows.
So conclusion, Don't use display:none; to hide your file input , you may use opacity:0 instead.
Just use this:
$(function() {
$('#watchButton').trigger('click');
});
You can't simulate a click event with javascript.
jQuery .trigger() function only fires an event named "click" on the element, which you can capture with .on() jQuery method.
I want to toggle text between bold and normal I made this code for it, but when I open my page the bold button disappears?
$("#bold").toggle(function() {
$('.focus').css("font-weight", $(this).val());
}, function() {
$('.focus').css("font-weight", "normal");
});
Is there something wrong with my code?
Please help, thanks in advance.
Assuming you're using jQuery 1.9 or later the problem is that the .toggle() event handling method was removed from the library. So what you're actually calling is the .toggle() function that hides/shows elements. (In earlier versions of jQuery both functions existed and jQuery figured out which one you meant based on the arguments passed in.)
You can implement your own toggle easily enough with a standard .click() handler:
$("#bold").click(function() {
var f = !$(this).data("toggleFlag");
if (f) {
$('.focus').css("font-weight", $(this).val());
} else {
$('.focus').css("font-weight", "normal");
}
$(this).data("toggleFlag", f);
});
This uses the .data() method to keep track of a boolean flag to indicate which code to execute. The very first time the click handler is called the flag will be returned as undefined because it hasn't previously been set, but we just convert that to a boolean with ! (assuming you want to execute the if and not the else case on the first click).
It disappears because that version of toggle is deprecated and removed, and in newer versions of jQuery all it does is toggle visibility.
You could do something like this instead :
var state = true;
$("#bold").on('click', function() {
$('.focus').css("font-weight", state ? this.value : 'normal');
state = !state;
});
FIDDLE
The only solution I fount to the disappearing element after click... is Callback function after the toggle effect finished.
here a link that explain the Callback function.
and here is my code:
jQuery('.menu li.item-487').click(function(){
jQuery('#main-menu .moduletable .menu li').toggle("slow",function(){jQuery('.menu li.item-487').css('display' , 'block');});
});
lets say I have
function trigger(){
$('a.pep').each(function(){
$('a.pep').click(function(){
console.log($(this).val());
});
});
}
function push(){
$('body').append('<a class="pep">hey mate i have no trigger yet</a>');
trigger(); //now i do but the others have duplicated trigger
}
$(document).ready(function(){
$('a.push').click(function(){
push();
});
});
So it seems that the click event is being applied twice/+ because the console.log is lauched more than once by click
How can i prevent this?
The problem is that you call $('a.pep').click() lots of times. (In fact, you bind as many click handlers as there are matching elements to each element. And then you do it again every time one of them is clicked.)
You should lever the DOM event bubbling model to handle this. jQuery helps you with the on method:
$(document.body).on('click', 'a.pep', function() {
console.log('element clicked');
$(document.body).append('<a class="pep">Click handlers handled automatically</a>');
});
See a working jsFiddle.
Note that I have removed the val call, because a elements can't have a value... Note also that the on method is introduced in jQuery 1.7; before that, use delegate:
$(document.body).delegate('a.pep', 'click', function() {
Small change to your trigger function is all you need. Just unbind the click event before binding to ensure that it is never added more than once. Also, you don't need to use each when binding events, it will add the event to each item automatically.
function trigger(){
$('a.pep').unbind('click').click(function() {
console.log($(this).val());
});
}
You can check using data('events') on any element if the required event is attached or not. For example to check if click event is attached or not try this.
if(!$('a.pep').data('events').click){
$('a.pep').click(function(){
console.log($(this).val());
});
}
you should use jQuery live here because you add DOM elements dynamicly and you want them to have the same click behaviour
function push(){
$('body').append('<a class="pep">hey mate i have no trigger yet</a>');
}
$(document).ready(function(){
$('a.push').click(function(){
push();
});
$('a.pep').live('click', function(){
console.log($(this).val());
});
});
Try:
if($('a.pep').data('events').click) {
//do something
}
i think if you use live() event you dont need to make function
$('a.pep').live('click', function(){
console.log($(this).val());
});
I've already looked at similar questions but the answers provided involve buttons and not div elements. When I click the div element with id click, the click event handler is disabled by unbind() and sets a timer for 2 seconds. After 2 seconds, the click event handler should be enabled again by bind(). The problem is that the click event handler doesn't seem to get "rebound". I am appending text to another div element to check if the click event handler is active.
Here is my JSFiddle.
Another approach to the whole problem is not to bother with unbinding and rebinding and just use a "disabled" flag:
$(document).ready(function(){
var clickDisabled = false;
$('#click').click(function(){
if (clickDisabled)
return;
// do your real click processing here
clickDisabled = true;
setTimeout(function(){clickDisabled = false;}, 2000);
});
});
Try this:
$(document).ready(function(){
$('#click').click(function(){
$('#click').unbind('click');
$('#status').append("unbound ");
setTimeout(
function(){
$('#click').bind('click',function(){
});
$('#status').append("bound ");
},
2000
);
});
});
You misspelled setTimeout and your "bound" message was being appended only on click.
I answer your question but just don't kill yourself :)) Just kidding... Your code is fine just a typo: setTimeOut should be setTimeout (the O should be o)
When you are rebinding the function the second time you are binding just a subset of all your code - all it does it output bound to the status, but it doesn't contain any of the code for doing a timeout a second time.
Also, you will like the .one() function.
I've fixed up your code here: https://jsfiddle.net/eQUne/6/
function bindClick() {
$('#click').one('click', function() {
$('#status').append("bound ");
setTimeout(bindClick, 2000);
});
}
$(document).ready(function(){
bindClick();
});
If I got what you were asking correctly, this should work:
<div id="click" >time out</div>
<div id="status"></div>
$(document).ready(function() {
$('#click').click(unbindme);
$('#status').html('bound');
function unbindme()
{
$('#click').unbind('click');
$('#status').html('unbound');
setTimeout(function(){
alert('here');
$('#status').html('bound');
$('#click').click(unbindme);
}, 2000);
}
}
Check it out here: https://jsfiddle.net/eQUne/
I am trying to add an onClick event to an anchor tag ...
Previously i had ...
<a href="somlink.html" onClick="pageTracker._link(this.href); return false;">
But i am trying to avoid the inline onClick event because it interferes with another script..
So using jQuery i am trying the following code ...
<script>
$(document).ready(function() {
$('a#tracked').attr('onClick').click(function() {window.onbeforeunload = null;
pageTracker._link(this.href);
return false;
});
});
</script>
with the html like so <a id="tracked" href="something.html">
So my question is should this be working, and if not what would be the best solution?
The correct way would be (as for jQuery)
$('#tracked').click(function() {
pageTracker._link($(this).attr('href'));
return false;
});
This will add an "onclick" event on any element with tracked id. There you can do anything you want. After the click event happens, the first line will pass href attribute of the clicked element to pageTracker.
As for your original question, it wouldnt work, it will raise undefined error. The attr works a bit different. See documentation . The way you used it, would return the value of the attribute and I think that in that case its not chainable. If you would like to keep it the way you had it, it should look like this:
$('#tracked').click(function() {
$(this).attr('onclick', 'pageTracker._link(this.href); return false;');
return false;
});
You can also try
var element1= document.getElementById("elementId");
and then
element1.setAttribute("onchange","functionNameAlreadyDefinedInYourScript()");
// here i am trying to set the onchange event of element1(a dropdown) to redirect to a function()
I spent some time on this yesterday. It turned out that I needed to include the jQuery on $(window).ready not $(document).ready.
$( window ).ready(function() {
$('#containerDiv a').click(function() {
dataLayer.push({
'event': 'trackEvent',
'gtmCategory': 'importantLinkSimilarProperties',
'gtmAction': 'Click',
'gtmLabel': $(this).attr('href')
});
});
});