I'm about to make a function on jQuery like this:
$(document).ready(function() {
$('#header_rules').click(function() {
// here i define myFunction()
});
});
<a id="header_rules" href="#">RULES</a>
instead of
<a id="header_rules" href="#" onClick="myFunction();return false">RULES</a>
But I don't know how to prevent scrolling to the top of the page using jQuery after someone clicks the link.
In fact, I'll total get rid about native JS, which could yield some trouble (that's why I use a JS framework like jQuery).
Any help? Cheers
Call e.preventDefault(); where e is the first argument of your click handler:
$(document).ready(function() {
$('#header_rules').click(function(e) {
e.preventDefault();
// here i define myFunction()
});
});
<a id="header_rules" href="#">RULES</a>
The below will also work, but it'll stop other click events on the item, I think.
(document).ready(function() {
$('#header_rules').click(function() {
// here i define myFunction()
return false;
});
});
What ThiefMaster said, and you could also inclue return false; inside your function intead of inline.
Related
I have a button where I am trying to add on click jquery as below
<button onclick="myFunction()">YES</button>
And
$(document).ready(function() {
function myFunction(){
$('#mycheckboxdiv').toggle();
$("div#headersteptwo").addClass("hidden");
}
})
However, on click I am getting Uncaught ReferenceError: myFunction is not defined
What am I doing wrong and how to fix this?
Updated with a sample jsfiddle
http://jsfiddle.net/3aC7W/1/
What am I doing wrong and how to fix this?
You are defining the function inside another function, i.e. the function is not defined in global scope and hence cannot be found by the inline event handler.
Just remove $(document).ready(function() { because you don't need it there:
function myFunction(){
$('#mycheckboxdiv').toggle();
$("div#headersteptwo").addClass("hidden");
}
You only have to use $(document).ready(function() { ... }); if you manipulate the DOM, and also only if you place the script before the elements in the HTML document.
The better solution of course would be to bind the event handler with jQuery (and not use inline event handlers):
$(document).ready(function() {
$('button').on('click', function(){
$('#mycheckboxdiv').toggle();
$("div#headersteptwo").addClass("hidden");
});
});
You might have to add a class or ID to the button to make the selector more specific. Have a look at the list of available selectors.
change your code to this way to achieve click :
<button id="myFunction">YES</button>
and
$(document).ready(function() {
$('#myFunction').click(function(e){
$('#mycheckboxdiv').toggle();
$("div#headersteptwo").addClass("hidden");
});
});
check it at: http://jsfiddle.net/aneesh_rr/XJ758/3/
change your code to this:
$(document).ready(function() {
window.myFunction = function(){ //you should make myFunction avaliable in global
$('#mycheckboxdiv').toggle();
$("div#headersteptwo").addClass("hidden");
}
})
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.
my a click jquery function is not working, it just doesn't give any errors at console at all too.
Here is the link -
Edit
and here is the click function
$('a').click(function() {
var item = $(this).attr("id");
alert(item);
return false;
});
It doesn't popout the alert box, nor it does show me error in console.
Okay, someone asked for more info -
The link is added with jquery, by pressing button, and as id it takes one of the input fields value and inserts it as link with id from input field. There are no duplicate ids, all javascript scripts are located at the end of head tag, and the a click function is located last in part.
Based on your edit that the <a> tag is being inserted dynamically, you'll need to use jQuery's .on() (jQuery version 1.7 and later) or .live() method to attach the click handler.
This code should work, so I suppose there is some other error before this code runs that prevents correct Javascript execution.
Edit: OR the DOM is not yet ready when you insert the Javascript code. Then you should use
$(function() {
$('a').click(function() {
var item = $(this).attr("id");
alert(item);
return false;
});
});
Are you wrapping it on the ready event or after the element has been displayed? If so then it should work;
http://jsfiddle.net/sWeRf/
Either place this code after the Edit on the page, or put it in the head with $(document).ready(function() { //Place code here. });
Can you try replacing your JS code with the following (put between the HEAD tags)
<script type="text/javascript">
$(document).ready(function(){
$('a#lang').click(function(){
alert($(this).attr('id'));
});
});
</script>
Are you checking the document is loaded before applying your JQuery click handler?
e.g.
$(document).ready(function() {
$('a').click(function() {
var item = $(this).attr("id");
alert(item);
return false;
});
});
Instead of using document.ready you can use an anonymous function that does the same thing.
Like this:
$(function() {
$('a').click(function() {
var item = $(this).attr("id");
alert(item);
return false;
});
});
To remove the item do this:
$('#language_c').remove();
my question is a short one but I couldn't figure it out by myself. I've got a function like -> http://jsfiddle.net/gtU56/ . I'm calling a javascript-function with an event-listener(onclick) in my html-code. The function itself is more complex but I need the last snippet. By clicking 'Show More' the text should change. Why won't the text change?
Because the toggleText function isn't available when the html code is rendered.
In other words the function isn't set until the page is ready so the onclick function doesn't reference anything.
Either have the function like here http://jsfiddle.net/gtU56/2/
or have it in the head of the page because its needs to be ready immediately
If you want it to wait for the ready state you can do the following and remove the onclick action all together
http://jsfiddle.net/gtU56/7/
$(".text").click(function()
{
$(".text").toggle();
});
toggleText = function () {
$('.text').toggle();
}
check here http://jsfiddle.net/gtU56/3/
It's because of how you're loading the function. Switch it from onLoad to no wrap (head) and it works fine.
jsFiddle example
Using jsFiddle's onLoad wraps your function in a window.onload call like this:
<script type="text/javascript">
//<![CDATA[
$(window).load(function(){
function toggleText() {
$('.text').toggle();
}
});//]]>
</script>
While no wrap (head) just adds it normally like this:
<script type="text/javascript">
//<![CDATA[
function toggleText() {
$('.text').toggle();
}
//]]>
</script>
since you are already claiming having jquery, you need not use inline javascript. try this
var elems = $('.text');
elems.click(function(){
elems.toggle();
});
fiddle : http://jsfiddle.net/gtU56/5/
$('.text').click(function() {
$('.text').toggle('slow', function() {
// do your animation..
});
});
Js Fiddle
This is the solution - http://jsfiddle.net/gtU56/6/
You need to first make sure that the function is registered after page load. Then, bind a click event to the div.
Hope this helps!
First you should organize you jQuery code like this:
$.(document).ready(function() {
// enter jQuery code here
});
Otherwise you're accessing a not completly loaded html document.
Also, you don't need the event-listener if you are using jQuery.
This should work for you:
$.(document).ready(function() {
$('.text').click(function() {
$(this).toggle();
});
});
Is very easy. You can use ID or CLASS.
onclick="$('NAME ID or CLASS').toggle(ANIMATION or DURATION);"
<div>
<div class="text" onclick="$('.text2').toggle(400);">Show More</div>
<div class="text2" style="display:none">Show Less</div>
</div>
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')
});
});
});