Detecting Event from HTML Element using jquery - javascript

I have a legacy code that has something like
<a href='#' onclick="javascript:Domystuff(); return false;"> Some text<a>
I add a jQuery for some other purpose in website, and now I want to detect if this given a tag has "onclick" event available or not. But I didn't found how can I do this. I see most suggest to use $("a").data('events') but that didn't work for me, and always give undefined. however when I call $("a").click() it does execute the Domystuff() function.
Any idea how can I detect if onclick or onchange or onblur like HTML attribute events are present or not.
EDIT: I forgot to mention that I don't just want to detect all events from attributes but I want all events on element for click or blur or change. Hope I make myself clear now. Thanks

if($('a').attr('onclick')) { // exists
}
after all, even eventhandlers are HTML - attributes.
Still, that won't detect eventhandlers attached by jQuery, so:
var ahrefs = $('a');
for(var i = 0;i < ahrefs.length;i++) {
var node = ahrefs.get(i);
if(typeof node.onClick == function) { // has an attached event handler
}
}
Easy, isn't it?

try something like this
if ($('a').attr("onClick") != undefined) {}

Related

Adding code via addEventListener without loop by mouseover

I want to add some code by addEventListener. I would use DOMContentLoaded, but ID which I'm trying to select is not available on page load. I could use mouseover, but it iterate the code on any move. I could also use click event, but I don't want it show on click, but just when it's shown. How can I handle it?
document.addEventListener("mouseover", function(event){
document.querySelector("#id").insertAdjacentHTML('afterend', '<div>asd</div>');
});
You need to delegate
var yourSpecificId = "some-id";
document.addEventListener("mouseover", function(event){
if (event.target.id == yourSpecificId ) //only when the id of the mouseover element is matching yourSpecificId
{
//code you want to execute
}
});
I would suggest a Mutation Observer. It looks hard to implement, but it's very easy. You can provide a callback function, and then a quick if statement to check if the newly added element has the correct id. If so, run your code and disconnect the observer.
It would be easier to help you if you posted a working example of when an element is added and the function you need to run.
Read this blog: https://davidwalsh.name/mutationobserver-api

JavaScript registering events handlers externally

I have decided to remove all calls to JavaScript event from the html form elements to an external file. In doing this i registered an event for each item. However access the elements attributes using 'this' can no longer be used what I have decided to use is event.target.value for value attribute and event.target.name for name attribute. I think this is not the best implementation since I am getting some adverse results from implementing it.
Under is my implemented code and more on the issue:
JavaScript Inline Event Handler (Before)
<input type="radio" name="rdb_NewUsers" value="1" list="#{'true':'Yes','false':'No'}" onclick="configureItemsForRadioButton(this.value, this.name)"
JavaScript Registered External Event Handler (After)
var configureRadioButtons = {
onClick:function(evt){
evt.stopPropagation();
console.log(evt.target.value + '||'+evt.target.name);
configureItemsForRadioButton(evt.target.value, evt.target.name);
}
};
dojo.connect(dojo.byId("rdbNewUser"), "onclick", configureRadioButtons, "onClick");
The problem I am facing is when I click on any button it actually executes the console.log(evt.target.value + '||'+evt.target.name); even though it is not an registered event for the button. I think using event.target refers to any event executed on the page. What else can be used instead of evt.target.value to refer to the object who fired the event's value and name.
If you're going to avoid using a DOM manipulation tool like jQuery (which I do not recommend) you can do the following:
var myButton = document.getElementById("myButton");
myButton.addEventListener('click', function(){alert('Hello world');}, false);
If you use jQuery (recommended) it would work like so:
$('#myButton').on('click', function() {alert('Hello world');});
I'm not sure what dojo.connect method does, but this is how you normally attach an event to an element on the page. From your code, it's hard to understand how exactly you are bind your events with the function.
var configureRadioButtons = {
onClick: function(e) {
e.stopPropagation();
console.log(e)
}
};
document.getElementById("someID").addEventListener('click', configureRadioButtons.onClick, false);
<button id="someID">Click me</button>
After reviewing my code i soon realized i had overlooked something very important. My radio buttons actually carry a different id at run time rdb_NewUserstrue and rdb_NewUsersfalse and i was not registering events for these elements hence the reason the event kept firing on any click event, it was not finding an element with the id rdb_NewUsers. My solution is under:
I query the DOM for all radio buttons and got their Ids and based on the event/radio button clicked i attached a function (all radio buttons are handled by one function). In this way i did not need to hardcode an id for the radio button.
var configureRadioButtons = {
onClick:function(evt){
evt.stopPropagation();
//console.log(evt.target.value + '||'+evt.target.name+ '||'+evt.keyCode);
configureItemsForRadioButton(evt.target.value, evt.target.name);
}
};
var radios = document.querySelectorAll('input[type=radio]');
for (var i = 0 ; i < radios.length ; i++){
//console.log(radios[i].id);
dojo.connect(document.getElementById(radios[i].id), "onclick",configureRadioButtons, "onClick");
}

Simulate click in javascript [duplicate]

I want to simulate a click on any link on a page using JavaScript. If that link has some function binded to its 'onclick' event (by any other JS I don't have any control over), then that function must be called otherwise the link should behave in the normal manner and open a new page.
I am not sure that just checking the value of the 'onclick' handler would suffice. I want to build this so that it works on any link element.
I have no control over what function maybe binded to the onclick event of the link using whichever JS library (not necessarily jQuery) or by simply using JavaScript.
EDIT: With the help of the answers below, it looks like it is possible to check for event handlers attached using jQuery or using the onclick attribute. How do I check for event handlers attached using addEventListener / any other JS library so that it is foolproof?
You can use the the click function to trigger the click event on the selected element.
Example:
$( 'selector for your link' ).click ();
You can learn about various selectors in jQuery's documentation.
EDIT: like the commenters below have said; this only works on events attached with jQuery, inline or in the style of "element.onclick". It does not work with addEventListener, and it will not follow the link if no event handlers are defined.
You could solve this with something like this:
var linkEl = $( 'link selector' );
if ( linkEl.attr ( 'onclick' ) === undefined ) {
document.location = linkEl.attr ( 'href' );
} else {
linkEl.click ();
}
Don't know about addEventListener though.
Why not just the good ol' javascript?
$('#element')[0].click()
Just
$("#your_item").trigger("click");
using .trigger() you can simulate many type of events, just passing it as the parameter.
Easy! Just use jQuery's click function:
$("#theElement").click();
Try this
function submitRequest(buttonId) {
if (document.getElementById(buttonId) == null
|| document.getElementById(buttonId) == undefined) {
return;
}
if (document.getElementById(buttonId).dispatchEvent) {
var e = document.createEvent("MouseEvents");
e.initEvent("click", true, true);
document.getElementById(buttonId).dispatchEvent(e);
} else {
document.getElementById(buttonId).click();
}
}
and you can use it like
submitRequest("target-element-id");
At first see this question to see how you can find if a link has a jQuery handler assigned to it.
Next use:
$("a").attr("onclick")
to see if there is a javascript event assigned to it.
If any of the above is true, then call the click method. If not, get the link:
$("a").attr("href")
and follow it.
I am afraid I don't know what to do if addEventListener is used to add an event handler. If you are in charge of the full page source, use only jQuery event handlers.
All this might not help say when you use rails remote form button to simulate click to. I tried to port nice event simulation from prototype here: my snippets. Just did it and it works for me.

Javascript attach event to class name

If I have 10 items, with the class name keyword:
<div class="keyword"></div>
How can I attach an event, for example click, on this element.
I tried the following, but with no luck: (no alert comes up)
document.getElementsByClassName('.keyword').onclick = function()
{
alert(true);
Search.addKey(this.getElementsByClassName('name')[0].innerHTML);
}
Requirements:
Without the onclick attribute
no jQuery or any other library
Note: the elements are not generated on page load. Their number can be different, each times you click a button for eg.
I need a way to attach to all tags with the class 'keyword' in the 'future'.
You should delegate the event. Try this:
if (document.body.addEventListener)
{
document.body.addEventListener('click',yourHandler,false);
}
else
{
document.body.attachEvent('onclick',yourHandler);//for IE
}
function yourHandler(e)
{
e = e || window.event;
var target = e.target || e.srcElement;
if (target.className.match(/keyword/))
{
//an element with the keyword Class was clicked
}
}
You can read more on event delegation on quirksmode.com. AFAIK, this is the best way of achieving what you're trying to achieve. This is how all the major libs (prototype, jQuery, ...) work behind the scenes
Update:
Here's the fiddle, it contains some more explanation. An interesting reference is this page. It helped me understand the way IE and W3C events differ and, crucialy, it helped me understand the value, and countless benefits of Event Delegation

jQuery attach function to 'load' event of an element

I want to attach a function to a jQuery element that fires whenever the element is added to the page.
I've tried the following, but it didn't work:
var el = jQuery('<h1>HI HI HI</H1>');
el.one('load', function(e) {
window.alert('loaded');
});
jQuery('body').append(el);
What I really want to do is to guarantee that another jQuery function that is expecting some #id to be at the page don't fail, so I want to call that function whenever my element is loaded in the page.
To clarify, I am passing the el element to another library (in this case it's a movie player but it could be anything else) and I want to know when the el element is being added to the page, whether its my movie player code that it is adding the element or anything else.
I want to attach a function to a
jQuery element that fires whenever the
element is added to the page.
You want the livequery plugin, which does just this. The recent live function is similar, except it won't call you when the element is added. We use it all the time-- works great.
You'll use $('h1').livequery(function() {alert('just added');});
I do not know that there is this type of event, what comes to mind is creating the event "el-load" based on this tutorial, and then extend "append" to know if the item has this event make the call to it.
Use LiveQuery (jQuery plugin), and attach a load event to ur dom element (h1), in this case.
try overwriting the append method so you can add your own event?
jQuery.extend(jQuery.fn, {
_append: jQuery.fn.append,
append: function(j) {
this._append(j);
j.trigger('append');
}
});
var el = jQuery('<h1>HI HI HI</H1>');
el.one('append', function(e) {
window.alert('loaded');
});
jQuery('body').append(el);
If the tag is being created via ajax, you can use a related node to subscribe to the ajaxSuccess event.
http://docs.jquery.com/Ajax/ajaxSuccess
$('#somenode').ajaxSuccess(function(){
if ($('h1').length > 0) { ... }
});
If it's just being added to the DOM by a local script, I'm not sure it's possible to observe it's creation, with the exception of using a timer to poll for it.
Depending upon the browsers you need to support there are DOMNodeInserted and DOMNodeInsertedIntoDocument events. Can't vouch for how well they work myself but theoretically you could bind to these events and then either check the new node and the possible subtree that was inserted, or just check the entire document again with a $(selector) of your choosing to detect the node you're waiting to see added.
Try these:
var el = jQuery('<h1>HI HI HI</H1>');
jQuery('body').append(el);
setTimeout(function(){
window.alert('loaded');
},1000);//delay execution about 1 second
or to be safe this one:
var el = jQuery('<h1>HI HI HI</H1>');
jQuery('body').append(el);
window.checker = setInterval(function(){
if($('someselector').length>0){ //check if loaded
window.alert('loaded');
clearInterval(window.checker);
}
},200);
basically, this will loop every 200ms until the selector gets result, and terminates the loop when the result is available

Categories

Resources