Identify HTML elements when event triggers - javascript

I have my app with tons of buttons/inputs/etc. with different events. I want to clearly identify each one of them which some event triggers on.
For example, when I have a piece of my app:
<div class="someClass">
<div>
<someOtherElement>
<div></div>
<div><button ng-click="someClickEvent($event)"></button></div>
</someOtherElement>
</div>
</div>
I want to identify somehow, which button I have just clicked:
function someClickEvent(e) {
// some identification code here
}
[edit]
Maybe I wrote this wrong... I want some identification like XPath or something that will point which button were triggered (for error logging purposes).
So when I click my button and some error occurs, I want to identify the button and log some information about it (e.g. div[0].someClass>div[0]>someOtherElement[0]>div[1]>button[0]).

You can get identify the button and log it by this:
$scope.clickFunc = function(event){
$scope.clickedElement = event.target.outerHTML;
};
DEMO: http://jsfiddle.net/rjdzuxaL/1/

Use ng-click instead on onclick
<button ng-click="myFunction($event)">test</button>
Working demo

Change HTML to:
<button ng-click="myFunction($event)">test</button> //onclick works on javascript. For Angularjs, use ng-click.
JS:
$scope.someClickEvent = function(e) {
// some identification code here
var element = e.target; // this will give you the reference to the element.
}
You should avoid handling DOM in the controller. Use directives for them.

Related

How to check for multiple ID attributes if they are being clicked with JavaScript?

I am trying to check for activity on any of some specific ID attributes on my webpage with JavaScript, and if they are activated, I want to execute some code. The code is working for a single attribute with document.querySelector but not for document.querySelectorAll.
I have tried the solutions posted here but without success, as I run into the following error:
Uncaught ReferenceError: Invalid left-hand side in assignment
My code is simple:
document.addEventListener('DOMContentLoaded', function(){
Array.from(document.querySelectorAll("#id_types, #id_cons_1")).forEach(button=>button.click()) = function() {
document.querySelector("#id_new_name").value= some_value_to_be_assigned
}})
What am I doing wrong?
There's no need for the DOMContentLoaded event handler, just put a script with the following at the end of the body (just before the closing body tag).
There is also no need for Array.from since forEach is supported on the node list returned from querySelectorAll().
Then, you need to set up a click event for each button as shown below (button.click() = function...., doesn't set up an event handler, it invokes a click event).
document.querySelectorAll("#id_types, #id_cons_1").forEach(function(button) {
button.addEventListener("click", function(event){
document.querySelector("#id_new_name").textContent = "some_value_to_be_assigned";
});
});
<button type="button" id="id_types">button</button>
<button type="button" id="id_cons_1">button</button>
<div id="id_new_name">some value</div>

<div> class button click

I am trying to use a userscript to click a button. According to inspect element, the button looks like:
<div class="q-w-btn cl"></div>
Conveniently, the web developer neglected to put an id in there, so I was not able to select it by the id and then use the click function (are they called functions in JavaScript? I'm not an expert in the language).
I have tried many, many, many different ways, and all of them have successfully failed to click the button.
Any help is greatly appreciated, thanks for reading about my problems.
You can get elements by class name as well in java Script like below
document.getElementsByClassName("q-w-btn");
but notice that this function will return all elements in the document having the specified class name in the form of an array. As a result if your document has only one element having this class then you need to get the first element like below.
document.getElementsByClassName("q-w-btn")[0];
And yes in java script it is called functions you can see the conventions in here http://javascript.crockford.com/code.html.
Please try the following code (Insert script before </body>):
var btn = document.querySelector('.q-w-btn.cl');
if (btn) {
btn.addEventListener('click', onButtonClick);
}
function onButtonClick(evt) {
console.log('the click event is trigger');
}
You can simply use document.getElementsByClassName('q-w-btn') and bind click event on it, something like -
var button = document.getElementsByClassName('q-w-btn')[0];
button.addEventListener('click', function () {
alert('here');
});
<div class="q-w-btn">Click me</div>
This (courtesy of Ramin) worked for me:
var btn = document.getElementsByClassName("q-w-btn")[0]; btn.click();
Thanks to everyone who helped me learn and come to this solution.

jQuery won't bind click to underscore template using .on() for items added via function

I'm using underscore to create some elements and appending them to a div with jQuery.
At the bottom of the page I'm using jQuery's .on() to respond to clicks on the elements.
$('.pickup').on('click',
function(e) {
alert("hello");
}
);
Via some user interaction (in Google maps), I've got to add more elements to the div and want them to respond to clicks as well. For some reason they do not. I've pared it all down on jsfiddle:
http://jsfiddle.net/thunderrabbit/3GvPX/
When the page loads, note that clicking on the lines in output will alert('hello') via jQuery.
But click the [add] button and the new lines do not respond to clicks.
My HTML
<div id="unit_2225" class="pickup">
<span>Click me; I was here first</span>
</div>
<script type="text/template" id="unit-template">
<div class="unit-item">
<span class="pickup">
<span>click us (<%= unit_id %>) via underscore</span>
</span>
</div>
</script>
<div id="divID">
</div>
<button>add</button>
My Javascript
var addUnitToDiv = function(key,val) {
console.log(val);
var template = _.template($('#unit-template').html(),val);
$('#divID').append(template);
}
var unit_ids = [{unit_id:'hello'},
{unit_id:'click'},
{unit_id:'us'},
{unit_id:'too'},
{unit_id:112}];
$.each(unit_ids, addUnitToDiv);
var unit_pids = [{unit_id:'we'},
{unit_id:'wont'},
{unit_id:'respond'},
{unit_id:'to'},
{unit_id:'clicks'},
{unit_id:358}];
createMore = function() {
$.each(unit_pids, addUnitToDiv);
}
$('.pickup').on('click','span',function() {
alert("hello");
});
$('button').click(createMore);
I found a similarly worded question but couldn't figure out how to apply its answer here.
Instead of binding events directly to the elements, bind one event to their container element, and delegate it:
$("#divID").on("click", ".pickup", function () {
// Your event handler code
});
DEMO: http://jsfiddle.net/3GvPX/3/
In this case, the event handler is only executed for elements inside of the container #divID that have the class "pickup".
And in your scenario, the elements are being added to the element with an id of "divID". Thus, where the two selectors came from.
This is handy because, as you've found out, dynamically adding elements doesn't magically bind event handlers; event handlers bound normally with .on() are only executed (bound) on those present at the time of binding.
It could even help if you change the delegated selector to "span.pickup" (if you know the elements will always be a <span> like in your template), so that the DOM is filtered by the tag name first.
Reference:
http://api.jquery.com/on/#direct-and-delegated-events
Working demo http://jsfiddle.net/u2KjJ/
http://api.jquery.com/on/
The .on() method attaches event handlers to the currently selected set of elements in the jQuery object. You can attach the handler on the document level.
Hope it fits the need, :)
code try the code changed below
$(document).on('click','.pickup',function() {
alert("hello");
});

Dijit ComboButton / DropDownMenu onclick misunderstanding

I've just begun to play around with Dojo. I simply wanted to display a dialog when an item in a Dijit ComboButton's DropDownMenu is clicked. I tried using dojo.connect to associate the onclick event with a function which would simply display a dialog with the text contained in the item, with no luck.
I've managed to get it working in a horrible way. All the work is now actually written to the onclick attribute manually. I'm clearly misunderstanding something here. This is what I currently have:
JS:
require(["dijit/form/Button", "dijit/form/FilteringSelect", "dijit/DropDownMenu", "dijit/MenuItem"]);
//if the following is defined inside dojo.ready, nothing happens
function getmail(text)
{
alert('No mail from '+text);
}
dojo.ready(function(){
//the following does nothing:
dojo.connect(dojo.query(".dijitMenuItemLabel"), "onclick", function(evt) {
console.log("mail item clicked");
alert('Blah');
//dojo.stopEvent(evt);
});
});
HTML:
<form method="POST">
<div data-dojo-type="dijit.form.ComboButton" id="getmail">
<span>Get All Mail</span>
<div data-dojo-type="dijit.DropDownMenu">
<div data-dojo-type="dijit.MenuItem"
data-dojo-props="onClick:function(){getmail(dojo.trim(dojo.query('.dijitMenuItemLabel', this.domNode)[0].innerHTML))}">
Yahoo</div>
<div data-dojo-type="dijit.MenuItem">Google</div>
</div>
</div>
</form>
What does it look like I am clearly misunderstanding about Dojo?
(Or maybe I'm making simple JavaScript mistakes)
JSFiddle
You should be able to do it with something like
var myButton = dijit.byId('getmail');
myButton.on('click', function(){ alert('clicked') });
My guess is that you confused dojo.byId and dijit.byId when you fetched your button - regular DOM nodes work when you conenct a lowercase 'onclick' but widgets fire a camel case 'onClick' event (the distinction is because dijits fire with some keyboard events, for accessibility).
However, for newer versions of Dojo it is probably best to stay away from dojo.connect and instead just use simpler ".on" API I showed.
Ah, and before I forget, it also looks like you could have forgotten to run the Dojo parser (or set parseOnLoad to true) so the button was never created. Can you provide a fully executable example on JSFiddle?

Need to add another onClick event

I have a checkbox, that is styled using onclick handler.
The issue I have is , I also want to fire a div simultaneously.. to display hidden message.
Kind of like: checkbox ( tick to go featured )
If ticked show featured div, else hide.
Code I have is:
<span id="checkboxWrap" class="styledCheckboxWrap"><input name="include" type="checkbox" id="checkbox" onclick="setCheckboxDisplay(this)" class="styledCheckbox" /></span>
Wanted to also fire the div like...:
onClick="toggle('feature');"
Can I chain onClick events to one click handler?
ie..
onclick="setCheckboxDisplay(this);toggle('feature');"
Or am I going round in circles.
Use event listeners. They're better anyway. :)
var check = document.getElementById('checkbox');
check.addEventListener('click', function () {
setCheckboxDisplay(this);
});
check.addEventListener('click', function () {
toggle('feature');
});
Ideally, you should try to start using unobstrusive javascript which basically means you separate the structure from function by moving your javascript inside a <script> tag or into a separate file. So your code would look like this and make it easier to read.
HTML
<span id="checkboxWrap" class="styledCheckboxWrap">
<input name="include" type="checkbox" id="checkbox" class="styledCheckbox" />
</span>
Script
<script>
$(function(){
$('.styledCheckbox').click(function(){
setCheckboxDisplay(this);
toggle('feature');
});
});
</script>
Yes, you can call multiple statements in the onclick attribute as long as they are semicolon-delimited. That gets unweildy though, so I'll usually define a new function to wrap the two into one call.
Just delegate this to a function that does all your work...
// Somewhere in the head of the file...
function doOnClickStuff(target) {
toggle('feature');
setCheckboxDisplay(target);
}
And then just have the onClick handler invoke that...
onClick="doOnClickStuff(target);"

Categories