click on a div with regular javascript - javascript

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.

Related

removing dynamic javascript tag does not remove attached events

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.

How to stop event propagation from within an anchor's href attribute without using onclick or onmousedown

Due to restrictions, even though it is something i avoid altogether, in a certain situation i have to use the javascript: syntax in a href attribute of an achor tag.
(EXPLANATION: In my CMS i use a rich text editor to allow the user to make changes to text elements, including links. In some cases specific javascript: calls are required and i banned onclick completely from the link editing features (to simplify the process for the user). However, as one of the links appears within a block that reacts to an onclick event, the thing double-fires)
Like this:
My problem is that this link is inside a container that already reacts to an onclick event. Therefore i wanted to pass the event object along to the doSomething() method, so that i could then use jQuery's
event.stopPropagation()
method.
Unfortunately however, it seems that passing the event object along
does not seem to work at all. Safari won't say anything while Firefox will report ReferenceError: event is not defined
I assume that this is the case because href="" is not a script-initiating attribute (such as onclick). The problem is that in this situation i won't be able to access the tag beyond what i already do.
Therefore i either need
1.) A way to pass the event object to the doSomething() function from within the href attribute
or
2.) A way to stop the event propagation right in that anchor (after its clicked) by other means.
Thank You for any constructive input!
You cannot stop event propagation from the href attribute because:
When the href code executes, it is not an event. It just executes that code, similar to the "location hack". Like entering javascript:doSomething() in the browser's address bar.
The href code executes after the events fire on the link -- including bubbling.
You can see that behavior in this jsFiddle. Note that mouseup, mousedown, and click all fire both for the link, and on the container when the link is clicked, before the href code executes.
If there are event listeners that you want to block, you'll have to find another way.
But, if you can append javascript to the document you can block the href using preventDefault().
For example:
jQuery, before version 1.7:
$("#container a").bind ("mousedown mouseup click", function (e) {
e.preventDefault();
} );
jQuery 1.7 and later:
$("#container a").on ("mousedown mouseup click", function (e) {
e.preventDefault();
} );
or (better):
$("#container").on ("mousedown mouseup click", "a", function (e) {
e.preventDefault();
} );
You can see this last version live at jsFiddle.
If you cannot alter the link itself (to use onclick) then your only option is to alter the onclick handler of the container.
Can you do something like
function containerClickHandler(e) {
e = e || event;
var el = e.target || e.srcElement;
if (el.nodeName === 'A' && someOtherMatchChecks) {
// eat event
}
else {
// process event
}
}
Well, this is an old question, but in my particular case I did find a hack around it, but it might only apply to a subset of situations. I have a div that has an onclick. But if an inside that div is clicked, I don't want that div's onclick to fire. Here is what I do:
function myOnClick () {
// loop over all <a>'s, and test if they are hovered over right now.
var allLinks = document.links;
var dont = 0;
for (var i = 0, n = allLinks.length; i < n; i++) {
// pure javascript test to see if element is hovered.
if(allLinks[i].parentElement.querySelector(":hover") === allLinks[i]) {dont = 1; }
};
if(dont)return;
// your stuff here, only fires when dont is false.
}
I learned about the queryselector trick here: https://stackoverflow.com/a/14800287/2295722
I don't know if there is a way to get the arguments if you write your javascript in href attribute. But you can get it as following in onclick, but as you say this isn't the best practice:
<a onclick="console.log(arguments)">your link</a>
in arguments array you'll get your event object.
here is a demo for you:
http://jsfiddle.net/tEw5J/1/

Catching the Click on DOM/HTML/BODY event on the iPad

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

Remove All onclick Events for an Element

var links = document.body.querySelectorAll("p.sourcelinks a.individual_source_link");
for(var i=0;i<links.length;i++)
{
links[i].onclick = null;
}
Is my current code, however it doesn't remove the onclick events. I have no idea what they will be since this is a greasemonkey script.
Your code only deals with events added by element.onclick case. What about events added with addEventListener (for standards compliant browsers) and attachEvent (for IE)?
You need to use removeEventListener and detachEvent to remove events as well as setting .onclick to null. Then all your bases will be covered.
This article would probably be useful:
http://www.computerhowtoguy.com/how-to-use-the-jquery-unbind-method-on-all-child-elements/
One part in particular is a recursive function that removes all click events. Remember that jQuery will remove click events IF the click event was created using jQuery. the function given in the article will remove both those created with jQuery and those that were not. The function given is this:
function RecursiveUnbind($jElement) {
// remove this element's and all of its children's click events
$jElement.unbind();
$jElement.removeAttr('onclick');
$jElement.children().each(function () {
RecursiveUnbind($(this));
});
}
You would call the function like this:
RecursiveUnbind($('#container'));
That function takes a jQuery object parameter, but you could easily change it up to pass a string as the name of the ID for the element, or however you think is best.
While this only addresses click events you could easily modify it to handle others or all.
That code doesn't work because of GM's sandbox. links is in an XPCNativeWrapper.
To get around this use setAttribute(), like so:
var links = document.body.querySelectorAll("p.sourcelinks a.individual_source_link");
for(var i=0;i<links.length;i++)
{
links[i].setAttribute ("onclick", null);
}
Note that click handlers that are set other ways, will need to be cleared other ways (removeEventListener(), for example).
Array.from(document.all).forEach(el=>{
el.onselectstart=null
el.oncontextmenu=null
document.oncontextmenu=null
})
here is the solution
Right click and select event bypassed
I am guessing you have either an href or a JavaScript function being called on the onClick for an <a> link.
You can remove either of these by removing the href tag, the onClick event or in this case both of them.
for(var i=0;i<links.length;i++)
{
links[i].href='#';
links[i].onclick = '';
}

jQuery "modify" event

So I recently took a closer look at JavaScript and jQuery and after that stumbled over the Firefox extension called Greasemonkey.
Well, let me explain what I mean with the "modifiy"-event: I've got 2-3 userscripts for a certain page installed which automatically look if the page has changed in any way and if it has, they load the new content and append it to the already loaded page (they modify the DOM).
So basically, my userscript needs to know when that happens but I don't know how I should do that. Are there any jQuery events for that? Help would be appreciated.
var orig;
$(function(){
orig = getContent();
})
function watchContent() {
var mod = getContent();
if (mod != orig){ resetContent(orig); }
setTimeout(watchContent,1000)
}
function resetContent(html) {
$("body").append( html );
}
function getContent() {
return $("body").html();
}
With jQuery events if you want the event to apply to new elements you would use the .live method, however jQuery 1.3 doesn't support blur, focus, mouseenter, mouseleave, change, or submit events as live events, and it's change that you will want to use. (change, submit, and blur/focus are on the roadmap for jQuery 1.4)
As an alternative you could use the liveQuery plugin.

Categories