I'm using jQuery to detect a click on the DOM - or let's every click.
$(document).click(function(){
alert("Click :-)");
});
This works pretty good in every browser except Safari for iPad/iPhone. I've also tried to apply the event on the html or body element - no way. How to detect a common click on the iPad/iPhone?
Best regards,
Jim
As I found on http://www.danwellman.co.uk/fixing-jquery-click-events-for-the-ipad/ you may test the user agent and use touchstart or click depending on the platform
var ua = navigator.userAgent,
event = (ua.match(/iPad/i)) ? "touchstart" : "click";
$(document).on(event, function (ev) {
...
});
These answers got me started on the right direction (first google for "jquery document.on ipad"), so thanks for that, but borrowing from this answer I simplified it to something like this:
$(document).on("click touchstart", function (ev) {
...
});
This would obviously produce undesired results if a platform (like Android or Windows Phone or something) supported both click and touchstart in the event bubble, so if anyone knows that let me know (and I'll fix my code and delete this answer! :)
You may use the touchstart event instead.
I have used this:
jQuery(document).on('touchstart',function(event){
//your code here
});
-also instead of "document" you can bind to any DOM object.
and this(from another forum answer):
var body = document.getElementsByTagName('body')[0];
if ("ontouchstart" in window) {
body.ontouchstart = function(){
//your code here
};
};
-again, you don't have to use 'body' you can assign a variable to an object by class this way:
var dd = document.getElementsByClassName('infoAction')[0];
$('html').click(function(){
alert("Click :-)");
});
This works for me, I tested it now.
Even works with no content on page, wherever you click on the page.
You can attach the click listener to the main wrapper element (say div that encloses all the components in your page).
<body><div onclick="void(0)">
... your page tags ...
</div></body>
There is a minor difference with others browsers behaviour: the document object will reveive click events only for tags located inside the "... your page tags ..." section.
In other words, suppose your html and body tags have a yellow background color, and their child tags have a red background color.
The document object will receive clicks on the red areas only. This is usually not a serious drawback.
Tested on an iPhone 3 only
Related
i'm creating an application where a user can make a html layout and attach javascript to it.
Now i'm trying to make it so when they click a button, they go to a preview mode where they can see it in action.. so when they click i add the javascript tag ( with their javascript) in the head of the iframe.. this all works fine!
But the problem is when they leave the preview mode, i remove the javascript tag, however when i have code like this:
$('#button').click(function()
{
alert("ok");
});
it still alerts ok when i click the html button (when not in previewmode!), which shouldn't happen!
It seems that when removing the javascript tag, the listeners aren't removed.. Or am i doing it wrong?
Now my question: is there a way to make it so these added eventlisterens are removed when i remove the script tag?
AND YES: i know you can remove eventhandlers with .off(), but since i already have event handlers attached, these will be removed also, and i don't want this!
So two options i can think off:
- rebuild the whole iframe
- store the eventhandlers that were added by the user and when leaving the preview mode, removing them.
Thanks in advance
Each time you "evaluate" JavaScript, it becomes part of the browser's "image", and whether the source is present on the page no longer matters. You need to manually unbind the event, or replace the html segment to which the event was bound.
To remove events from an html element, you can use:
element.parentNode.innerHTML = element.parentNode.innerHTML
This rebuilds the DOM tree using the same HTML.
you need to unbind event.
You can do it by using jquery unbind() or off()
like this:
$("#button").unbind("click");
or
$("#button").off("click");
Demo: http://jsfiddle.net/a6NJk/664/
jquery Doc: http://api.jquery.com/off/
Another good answer: Best way to remove an event handler in jQuery?
Set the event:
var $button = $('#button');
$button.on("click", function() {
alert("ok");
});
Take off the event:
$button.off("click");
You can take off that specific function too
var $button = $('#button');
var eventFunction = function() {
alert("ok");
});
// Set event up
$button.on("click", eventFunction);
// Take event off
$button.off("click", eventFunction);
If you want to remove all events from an element you can use
$("#yourSelector").off()
Because it's not jQuery in general but also vanilla javascript, it would be too much work to keep track of javascript changes, so rebuilding the iframe would be the best option here.
I'm using curtain.js and would like to keep a DIV (which holds navigation) visible at all times except for when the user is looking at the very first panel, i.e. at the top of the page.
Currently the DIV resides within panel two
I'm thinking perhaps of using the hash change as you scroll through the page to trigger an append to the body. Curtain.js creates an individual URL for each panel and the URL changes each time a panel is brought into view.
I can append the div to the body (below) but I need to work out when to do this but I am unsure how? Could anyone help me out?
$("body").append($('.nav-wrap'));
you can use onhashchange event:
The hashchange event fires when a window's hash changes
$(window).bind('hashchange', function() {
$("body").append($('.nav-wrap'));
})
You can use JQuery to bind the Event
$(window).bind('hashchange', function(){ ... });
And add some workarounds for when it doesn't have the onhashchange event.
jQuery - hashchange event
Ok well instead of using some hacky solution, after much digging around in the plugin's file, I just added:
$("body").append($('.nav-wrap'));
to the setHash function on line 491. Works a treat.
I'm using jQuery 1.7.2 with Zoomy and jmpress plugins. Also I'm using boilerplate+bootstrap downloaded from initializr.com
I'm trying to create a "game" like [Waldo/Wally] when you have to find some character in a photo. Each photo has a different character to find.
I'm using jmpress as a presentation plugin to go from one photo to another every time the character is found. jmpress loads the content trough ajax (and I need that behavior) because I want a pretty fast load of the web.
Problem: The .on("click") event is not being caught on one of the elements that exist inside the content loaded.
As an example, I'll explain my problem with one of this characters (just taking parts of code).
I have in my index.html some divs to load the characters, I'll take the nurse character:
<div id="nurse" class="step container" data-src="women/nurse.html" data-x="7500">
Loading...
</div>
The jmpress load the data-src (women/nurse.html) trough ajax when the user is near to that div (step). It loads great.
This is the code of nurse.html
<script type="text/javascript">
new Image().src = "img/nurse_big.jpg";
</script>
<div class="descripcion">
<p>Bla, bla, bla.</p>
</div>
<div class="imagen">
<img src="img/nurse.jpg" alt="Find the nurse" />
</div>
As you can see, I have two divs loaded inside the #nurse div (that has .step class).
I have this code on my js/script.js file when I try to catch the click event:
$(".step").on("click", function(event){
console.log(event.target);
});
I'm also trying with "body" tag to see what happens
$("body").on("click", function(event){
console.log(event.target);
});
If you check the console while the message is showing (div.descripcion) it catch the event and print. But, after the div.descripcion is removed and the image appears, it dosen't. Like if that div.imagen or even elements inside it dosen't exist. The click event is not catched. I tried to catch mousemove event and It does.
Why is not catching the click? any idea?
You can see a working version: [Removed]
And the not working version: [Removed]
UPDATE: I forgot, if I use .on("click") it dosen't work. But if I use .on("mousemove") for example, it works. That's the weird part. .on() is working, but not for the click event.
UPDATE 2: I have removed the links of the live examples because they where dev versions. I'll publish the link to the final work when is published. Thanks to all of you for taking the time. Specially to #Esailija that gives me the answer.
Once again, you need to use on for content loaded later on:
$("body").on("click", ".step", function(event){
console.log(event.target);
});
Replace body with the closest static element that holds the .step elements.
Static means exist in the DOM when the you execute the line:
$(...).on("click", ".step", function(event){
Example:
$('#ContainerId').on("click", ".step", function(event){
// Do what you want.
});
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers
on docs
The zoomy plugin you are using does this:
'click': function () {
return false;
}
Since the element you are clicking when you are on the image, is actually the zoomy elements, those get to handle the events first. They handle it by returning false, which means doinge.stopPropagation() as well as e.preventDefault(). So the event won't even come to .imagen.
There is also unterminated multi-line comment in your code, not sure what that does but it can't be good. Consider just deleting code instead of commenting it out.
Anyway, clearing everything like this:
$.cache = {}; //Can also do $("*").off() I think
And then doing:
$(".step").on("click", ".imagen", function(event){
console.log(event.target);
event.preventDefault();
});
And it works fine. You might wanna edit the plugin to do this instead:
'click': function (e) {
e.preventDefault();
}
Alternatively you could look for a plugin that is developed by someone who knows what the hell they are doing or write it yourself.
In the documentation in http://zoomy.me/Options.html you can allow the plugin to have a clickable area by adding in true to the clickable option.
So when calling zoomy() on a element all you have to do is add a little bit of code inside the zoomy function.
$('.element').zoomy({clickable:true});
and that should fix everything,
The alternative way to catch the function on click event is just like below.
<div onclick="fireClickEvent();" > Just firing the click event!</div>
function fireClickEvent() {
console.log(event.target);
}
jquery attaches a click method on even things that aren't typically clickable like a DIV. this can be great because some things respond to that. How can i "click" on any old regular DIV using plain old javascript without Jquery?
what i am trying to do is trigger clicking on the area where the user can post in Jquery. I'm using a chrome extension that can run some javascript on a hotkey. I wrote a jquery version
var x = $('div[guidedhelpid="sharebox"]'); x.click();
which works fine, other than it seems that the jquery library only loads about 1/4 of the time. not sure why, so i figured i'd try to make it in plain JS. As for the handler, googles own code is intercepting and processing the clicks fine, and it works in the Jquery version. so i just want to effectively do the same thing.
does Jquery internally go up or down the DOM until it finds the first think clickable?
update
in light of it, i was looking in the wrong direction, and really just needed to find the right element to focus on (in JQUERY).
If you just want to bind one function to the element, you could use
var element = document.getElementById("el"); //grab the element
element.onclick = function() { //asign a function
//code
}
but if you need to attach more than one event, you should use addEventListener (eveything except IE) and attachEvent (IE)
if(element.addEventListener) {
element.addEventListener("click", function() {});
} else {
element.attachEvent("onclick", function() {})
}
The click() function is built in JavaScript, not jQuery.
HTMLElementObject.click()
Source.
var d = document.getElementById("test");
d.onclick = function(){alert('hi');};
var divElement = document.getElementById('section');
divElement.addEventListener('click', function () {
alert('div clicked');
},false);
I use tables to control the page layout. The "td" are clickable, so I write my "onclick = whatever()" in the td tag and not in the div tag.
I have a timer in my JavaScript which needs to emulate clicking a link to go to another page once the time elapses. To do this I'm using jQuery's click() function. I have used $().trigger() and window.location also, and I can make it work as intended with all three.
I've observed some weird behavior with click() and I'm trying to understand what happens and why.
I'm using Firefox for everything I describe in this question, but I am also interested in what other browsers will do with this.
If I have not used $('a').bind('click',fn) or $('a').click(fn) to set an event handler, then calling $('a').click() seems to do nothing at all. It does not call the browser's default handler for this event, as the browser does not load the new page.
However, if I set an event handler first, then it works as expected, even if the event handler does nothing.
$('a').click(function(){return true;}).click();
This loads the new page as if I had clicked the a myself.
So my question is twofold: Is this weird behavior because I'm doing something wrong somewhere? and why does calling click() do nothing with the default behavior if I haven't created a handler of my own?
As Hoffman determined when he tried to duplicate my results, the outcome I described above doesn't actually happen. I'm not sure what caused the events I observed yesterday, but I'm certain today that it was not what I described in the question.
So the answer is that you can't "fake" clicks in the browser and that all jQuery does is call your event handler. You can still use window.location to change page, and that works fine for me.
Another option is of course to just use vanilla JavaScript:
document.getElementById("a_link").click()
Interesting, this is probably a "feature request" (ie bug) for jQuery. The jQuery click event only triggers the click action (called onClick event on the DOM) on the element if you bind a jQuery event to the element. You should go to jQuery mailing lists ( http://forum.jquery.com/ ) and report this. This might be the wanted behavior, but I don't think so.
EDIT:
I did some testing and what you said is wrong, even if you bind a function to an 'a' tag it still doesn't take you to the website specified by the href attribute. Try the following code:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
/* Try to dis-comment this:
$('#a').click(function () {
alert('jQuery.click()');
return true;
});
*/
});
function button_onClick() {
$('#a').click();
}
function a_onClick() {
alert('a_onClick');
}
</script>
</head>
<body>
<input type="button" onclick="button_onClick()">
<br>
<a id='a' href='http://www.google.com' onClick="a_onClick()"> aaa </a>
</body>
</html>
It never goes to google.com unless you directly click on the link (with or without the commented code). Also notice that even if you bind the click event to the link it still doesn't go purple once you click the button. It only goes purple if you click the link directly.
I did some research and it seems that the .click is not suppose to work with 'a' tags because the browser does not suport "fake clicking" with javascript. I mean, you can't "click" an element with javascript. With 'a' tags you can trigger its onClick event but the link won't change colors (to the visited link color, the default is purple in most browsers). So it wouldn't make sense to make the $().click event work with 'a' tags since the act of going to the href attribute is not a part of the onClick event, but hardcoded in the browser.
If you look at the code for the $.click function, I'll bet there is a conditional statement that checks to see if the element has listeners registered for theclick event before it proceeds. Why not just get the href attribute from the link and manually change the page location?
window.location.href = $('a').attr('href');
Here is why it doesn't click through. From the trigger function, jQuery source for version 1.3.2:
// Handle triggering native .onfoo handlers (and on links since we don't call .click() for links)
if ( (!elem[type] || (jQuery.nodeName(elem, 'a') && type == "click")) && elem["on"+type] && elem["on"+type].apply( elem, data ) === false )
event.result = false;
// Trigger the native events (except for clicks on links)
if ( !bubbling && elem[type] && !event.isDefaultPrevented() && !(jQuery.nodeName(elem, 'a') && type == "click") ) {
this.triggered = true;
try {
elem[ type ]();
// Prevent Internet Explorer from throwing an error for some hidden elements
}
catch (e)
{
}
}
After it calls handlers (if there are any), jQuery triggers an event on the object. However it only calls native handlers for click events if the element is not a link. I guess this was done purposefully for some reason. This should be true though whether an event handler is defined or not, so I'm not sure why in your case attaching an event handler caused the native onClick handler to be called. You'll have to do what I did and step through the execution to see where it is being called.
JavaScript/jQuery doesn't support the default behavior of links "clicked" programmatically.
Instead, you can create a form and submit it. This way you don't have to use window.location or window.open, which are often blocked as unwanted popups by browsers.
This script has two different methods: one that tries to open three new tabs/windows (it opens only one in Internet Explorer and Chrome, more information is below) and one that fires a custom event on a link click.
Here is how:
HTML
<html>
<head>
<script src="jquery-1.9.1.min.js" type="text/javascript"></script>
<script src="script.js" type="text/javascript"></script>
</head>
<body>
<button id="testbtn">Test</button><br><br>
Google<br>
Wikipedia<br>
Stack Overflow
</body>
</html>
jQuery (file script.js)
$(function()
{
// Try to open all three links by pressing the button
// - Firefox opens all three links
// - Chrome only opens one of them without a popup warning
// - Internet Explorer only opens one of them WITH a popup warning
$("#testbtn").on("click", function()
{
$("a").each(function()
{
var form = $("<form></form>");
form.attr(
{
id : "formform",
action : $(this).attr("href"),
method : "GET",
// Open in new window/tab
target : "_blank"
});
$("body").append(form);
$("#formform").submit();
$("#formform").remove();
});
});
// Or click the link and fire a custom event
// (open your own window without following
// the link itself)
$("a").on("click", function()
{
var form = $("<form></form>");
form.attr(
{
id : "formform",
// The location given in the link itself
action : $(this).attr("href"),
method : "GET",
// Open in new window/tab
target : "_blank"
});
$("body").append(form);
$("#formform").submit();
$("#formform").remove();
// Prevent the link from opening normally
return false;
});
});
For each link element, it:
Creates a form
Gives it attributes
Appends it to the DOM so it can be submitted
Submits it
Removes the form from the DOM, removing all traces *Insert evil laugh*
Now you have a new tab/window loading "https://google.nl" (or any URL you want, just replace it). Unfortunately when you try to open more than one window this way, you get an Popup blocked messagebar when trying to open the second one (the first one is still opened).
More information on how I got to this method is found here:
Opening new window/tab without using window.open or window.location.href
Click handlers on anchor tags are a special case in jQuery.
I think you might be getting confused between the anchor's onclick event (known by the browser) and the click event of the jQuery object which wraps the DOM's notion of the anchor tag.
You can download the jQuery 1.3.2 source here.
The relevant sections of the source are lines 2643-2645 (I have split this out to multiple lines to make it easier to comprehend):
// Handle triggering native .onfoo handlers (and on links since we don't call .click() for links)
if (
(!elem[type] || (jQuery.nodeName(elem, 'a') && type == "click")) &&
elem["on"+type] &&
elem["on"+type].apply( elem, data ) === false
)
event.result = false;
You can use jQuery to select the jQuery object for that element. Then, get the underlying DOM element and call its click() method.
By id:
$("#my-link").each(function (index) { $(this).get(0).click() });
Or use jQuery to click a bunch of links by CSS class:
$(".my-link-class").each(function (index) { $(this).get(0).click() });
Trigger a hyperlink <a> element that is inside the element you want to hookup the jQuery .click() to:
<div class="TopicControl">
<div class="articleImage">
<img src="" alt="">
</div>
</div>
In your script you hookup to the main container you want the click event on. Then you use standard jQuery methodology to find the element (type, class, and id) and fire the click. jQuery enters a recursive function to fire the click and you break the recursive function by taking the event 'e' and stopPropagation() function and return false, because you don't want jQuery to do anything else but fire the link.
$('.TopicControl').click(function (event) {
$(this).find('a').click();
event.stopPropagation();
return false;
});
Alternative solution is to wrap the containers in the <a> element and place 's as containers inside instead of <div>'s. Set the spans to display block to conform with W3C standards.
It does nothing because no events have been bound to the event. If I recall correctly, jQuery maintains its own list of event handlers that are bound to NodeLists for performance and other purposes.
If you need this feature for one case or very few cases (your whole application is not requiring this feature). I would rather leave jQuery as is (for many reasons, including being able to update to newer versions, CDN, etc.) and have the following workaround:
// For modern browsers
$(ele).trigger("click");
// Relying on Paul Irish's conditional class names,
// <https://www.paulirish.com/2008/conditional-stylesheets-vs-css-hacks-answer-neither/>
// (via HTML5 Boilerplate, <https://html5boilerplate.com/>) where
// each Internet Explorer version gets a class of its version
$("html.ie7").length && (function(){
var eleOnClickattr = $(ele).attr("onclick")
eval(eleOnClickattr);
})()
To open hyperlink in the same tab, use:
$(document).on('click', "a.classname", function() {
var form = $("<form></form>");
form.attr(
{
id : "formid",
action : $(this).attr("href"),
method : "GET",
});
$("body").append(form);
$("#formid").submit();
$("#formid").remove();
return false;
});