We are using asp.net webforms.
Server is generating input element (image) with onclick event.
When click occurs I'm calling function and passing event object into it.
Inside that function I am trying to access event.srcElement.className to get the class name of the element that caused the event.
Only in IE8 event's srcElement is null.
What would be the possible solution to this problem?
How can I get the class name of the element that caused the click event inside the function that is called when event occurs?
Selected answer solves my problem but doesn't answer the question!
Instead of using the event, just pass the clicked element to the javascript function.
<input type="button" onclick="func(this)" value="Ok" class="myClass"/>
Then directly access the element's style class.
<script>
function func(elem) {
alert(elem.className);
}
</script>
You could use jQuery library wich would help with cross browser issues. Using jQuery you could use event.target and all of it's properties. Problem to this is inconsistent DOM API across various browsers.
In jQuery you could do like this:
$(selector).click(function(event){
console.log(event.target.className);
console.log(event.target.classList);
});
Related
I have installed two separate userscripts, each requiring to invoke some code with document.body.onkeydown. However, I've noticed that with both userscripts enabled, only the latter event handler gets called.
Apparently, both userscripts are sharing the same DOM. This is contrary to my experience with Chrome extensions, where each Chrome extension has its own sandbox.
Either way, now how do I to fix this problem? I want both handlers to fire, and remain separate from each other.
I am executing my userscripts inside an IIFE with use strict mode enabled.
Using document.body.keydown will set the callback to the keydown event. Setting it again will replace the old one. Hence the latter script's event callback gets fired.
Instead use, document.body.addEventListener(<callback>) in both so, both the events will present.
In the below example, first keydown will get overridden by the second one. The addEventListener will append an listener to the keydown event. So on pressing a only 3rd event fired. On pressing b, both 2nd and 3rd are fired.
This is because the events added via the older method is added as like attribute values. Like,
<button id="show" onclick="show()">Click</button>
Hence, it got replaced.
The addEventListener adds the listener to the list of EventListners of the DOM Object.
In the example I replaced the onclick attribute with the function hide via the older method, hence it calls only the hide method.
For more info, please refer MDN Docs
document.body.onkeydown = function(event){if(event.key=="a")console.log("keydown")};
document.body.onkeydown = function(event){if(event.key=="b")console.log("b keydown")};
document.body.addEventListener("keydown",function(){console.log("addEventListener")})
function show(){console.log("show")}
function hide(){console.log("hide")}
var element = document.getElementById("show");
element.onclick=hide;
<button id="show" onclick="show()">Click</button>
You can change them to use
document.body.addEventListener("keydown", function(){ ... })
If they use the 'this' set in the onkeydown approach, you may need to make sure that is set correctly
document.body.addEventListener("keydown", (function(){ ... }).bind(document.body))
I am testing a component which has a click input on a div.
<div (click)="handleClick(someArgs)"></div>
Now I want to validate the behaviour in a test. I tried using .click() on the native element:
const elem = fixture.debugElement.query(By.css('my-selector'));
elem.nativeElement.click();
// Check for desired changes
However this only works in specific browsers since .click() seems to only be defined for HTMLInputElements (Relevant StackOverflow). I get the following error 'undefined' is not a function (evaluating elem.nativeElement.click()') for a couple browsers.
What is the best way to invoke a click event on a non HTMLInputElement?
I think the best way is calling triggerEventHandler() on DebugElement
triggerEventHandler
Triggers the event by its name if there is a corresponding listener in
the element's listeners collection. The second parameter is the event
object expected by the handler.
If the event lacks a listener or there's some other problem, consider
calling nativeElement.dispatchEvent(eventObject)
From testing documentation
https://angular.io/docs/ts/latest/guide/testing.html#!#trigger-event-handler
Usually when you want to trigger click on html elements using plain js you have to call the event which is defined on the element.
UPDATE: if you are using Jasmine, you can try calling trigger on the element:
const elem = fixture.debugElement.query(By.css('my-selector'));
elem.nativeElement.trigger('click');
I'm trying to make it so when an element gets focus it calls a function which then will take care of all other events - here is my code for now.
<span id="checkbox" class="checkbox" onFocus="cbHover(checkbox)"></span>
<script type="text/javascript">
function cbHover(id) {
if(document.getElementById(id).onClick) {
document.getElementById(id).style.backgroundPositionY = '-63px';
}
}
</script>
Obviously this isn't working :( So is there a way to keep the function running to listen for other events?
Thanks!
When the object is clicked, it is already focused. You can either skip the onFocus and replace it with onClick, or the other way around and remove if(document.getElementById(id).onClick) from the code, because you don't need it.
You are able to use two events: onFocus and onLostFocus. In onFocus event handler you are able to add onClick event to element:
document.getElementById(id).addEventListener('click',function_name,true);
In onLostFocus event handler you are able to remove event
document.getElementById(id).removeEventListener('click',function_name,true)
this is a bad idea even if you did get it to work you run the risk of applying multiple clicks on the same element. your best bet it to just apply the click event on dom ready I typically use jQuery
so if I where doing this in jquery i would do it like this
$(document).ready(function(){
$('.classname').click(function(){
// what to do onclick
});
});
The reason it isnt working is the parameter that is passed, should be enclosed in quotes.
It should be
onFocus="cbHover('checkbox')"
otherwise, javascript treats checkbox as a variable and tries to pass the value of the variable which is null.
I am trying to set an event in JavaScript but it is not really working. I am pretty sure I am doing it correctly too.
// in index.htm:
function foo() {
// Load gets code from a php file via ajax
document.getElementById('div').innerHTML = load('phppage.php');
document.getElementById('element').onClick = func;
}
// in lib.js:
function func() { alert('Working'); }
Unfortunately... it never alerts 'Working'. I have Google Chrome and I even inspected the element in the developer tools and found that the onClick property was infact func()... I don't understand why this wont work.
I do have extensive use of ajax. The element 'element' is actually loaded with ajax
Try changing it to "onclick"
HTML attributes are not, but javascript properties are case-sensitive. You need to use onclick to set the event handler.
I think the onclick property is lowercase.
However, you should use event attaching methods.
element.addEventListener('click',func);
(and attachEvent for Internet Explorer)
Of course, there are plenty of frameworks out there to handle the cross browser issues for doing this, such as:
ExtJS
JQuery
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.