onclick event: select item to be clicked by id - javascript

I have a button with name="testo_da_inviare" and I can trigger it's click event with:
document.forms['form_da_ricordare'].elements['testo_da_inviare'].onclick
Now I want to replace the button element with an a element that doesn't support the name attribute. So I gave the a element the id="testo_da_inviare"
How do I have to edit my js to trigger the onclick? Javascript is not my cup of tea and I am still learning how to use plain javascript.

You can use getElementById to select it:
document.getElementById('testo_da_inviare').onclick

If you want to fire an event of an element, the right way is to use dispatch method or createEventObject, not to call the element handler name
var eventName = "click";
var element = document.getElementById("testo_da_inviare");
if (document.createEventObject) {
// Dispatch for IE
var evt = document.createEventObject();
element.fireEvent("on" + eventName, evt);
}
else {
// Dispatch for firefox + others
var evt = document.createEvent("HTMLEvents");
// Event type, bubbling, cancelable
evt.initEvent(eventName, true, true);
element.dispatchEvent(evt);
}

1- You can let the onclick event trigger on the link/button itself like this:
description
<button onclick="thefunct()">description</button>
function thefunct() {
alert("button clicked");
}
2- Or on the script like this:
document.getElementById("id").onclick = function thefunct(){ alert('button clicked'); };
3- Or using an eventlistener like this:
document.getElementById("id").addEventListener("click", thefunct);
function thefunct() {
alert('button clicked');
}
4- Or using jQuery like this:
$("#id").click(function(){
alert('button clicked');
});
<script src="http://code.jquery.com/jquery-2.2.1.min.js"></script>

Related

How to get id of clicked button in winjs

I have several buttons in my WinJS page.
<button id="btn1">
Button 1
</button>
<button id="btn2"">
button 2
</button>...
and javascript to add click event to clicked button:
(function () {
WinJS.UI.processAll().done(function () {
var showButton = document.querySelector("xxx");
showButton.addEventListener("click", function () {
});
});
})();
How do i determine what button is clicked and set value of "xxx" to id of that button (btn1, btn2 etc...)
If I understood you correctly, you want to identify the button (sender) when you have multiple buttons that are attached to a single event handler.
MSDN:
In JavaScript, Windows Runtime event arguments are represented as a
single event object. In the following example of an event handler
method, the ev parameter is an object that contains both the sender
(the target property) and the other event arguments. The event
arguments are the ones that are documented for each event.
So you need to define an argument for the event handler and use its target property.
Let's say you have the following HTML:
<div id="label1"/>
<div>
<button id="button1">Button1</button><br />
<button id="button2">Button2</button><br />
<button id="button3">Button3</button><br />
</div>
and attached a single event handler to all of the buttons:
var button1 = document.getElementById("button1");
button1.addEventListener("click", buttonClickHandler);
var button2 = document.getElementById("button2");
button2.addEventListener("click", buttonClickHandler);
var button3 = document.getElementById("button3");
button3.addEventListener("click", buttonClickHandler);
you can access to sender in this way:
function buttonClickHandler(eventInfo) {
var clickedButton = eventInfo.target;
var label1 = document.getElementById("label1");
label1.innerHTML = clickedButton.id.toString();
}
Here's a WinJS solution to get the buttons :
var buttons = WinJS.Utilities.query('button');
Then you can bind the event to the buttons click :
buttons.forEach(function (btn) {
btn.addEventListener("click", function () {
console.log('button ' + this.id + ' has been clicked.');
})
});
I am new to WinJS, so there is probably a prettier solution to replace the forEach.
Something like this should work. querySelector only returns the first match, so you need to use querySelectorAll (see docs).
var buttons = document.querySelectorAll("button");
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener("click", function () {
var id = this.id;
// do stuff with "id"
});
}
You might also consider looking into jQuery as that can make things like this a little bit cleaner.

Select Tag Change Event Call on Selected Index Change

I have a select tag that has an eventListener on change.
Now I also have two different buttons that change it, that uses:
(selectTag).selectedIndex++;
The above does what I want to achieve, but it does not call my function callback on change.
How would I go about doing that? Other Approaches welcomed.
I would prefer pure-JS solutions, (noJquery please).
Just trigger change event when calling click handler on buttons:
var select = document.querySelector("select");
var button = document.querySelector("button")
select.addEventListener("change", function (e) {
alert(e.target.value)
});
button.addEventListener("click", function () {
var event;
try {
event = new Event("change")
} catch (e) {
event = document.createEvent("Event");
event.initEvent("change", true, false);
}
select.selectedIndex++;
select.dispatchEvent(event);
});
JS Bin
Update: I've changed it work in IE 10 and probably some others.

How to use jQuery's on(..) to dynamically bind to multiple events

I am trying to create leverage jQuery's .on() (ex-live()) to bind multiple events. It is working for elements which exist on document.ready, but if I dynamically add a second link after page load, my event handler isn't triggered.
This makes sense since the outer-most method iterates over the elements, and doesn't listen for newly added DOM nodes, etc. The .on(..) is what listens for new DOM nodes, but requires an event name params, which I don't have until I have the DOM node.
Seems like a chick and the egg sort of situation.
Thoughts?
Test 1
Test 2
$(function() {
$('.js-test').each(function() {
var $this = $(this);
var e, events = $this.data('test-events');
for(e in events) {
$this.on(events[e], function() {
console.log("hello world!")
});
}
});
});
Update, The following does seem work either; $(this) doesn't appear to be in the right scope.
Test 1
Test 2
$(function() {
$('.js-test').on($(this).data('test-events'), function() {
// call third party analytics with data pulled of 'this'
});
});
Update 1:
I think my best bet will be to create special .on methods for all the methods I want to support like so:
$(document).on('click', '.js-test[data-test-events~="click"]' function(event) {
record(this, event);
});
$(document).on('mouseover', '.js-test[data-test-events~="mouseover"]', function(event) {
record(this, event);
});
... etc ...
$('a.js-test').on('click mouseover', function(event) {
// you can get event name like following
var eventName = event.type; // return mouseover/ click
console.log(eventName);
// you code
console.log('Hello, World!');
});
Sample example
If you want something like live event then:
$('body').on('click mouseover', 'a.js-test', function(event) {
// you can get event name like following
var eventName = event.type; // return mouseover/ click
console.log(eventName);
// you code
console.log('Hello, World!');
});
According to your last edit try this:
$('.js-test').on($('.js-test').data('test-events'), function() {
console.log("hello world!")
});
Sample example for edit
and for live event delegation
$('body').on($('.js-test').data('test-events'), '.js-test', function() {
console.log("hello world!")
});
Afraid you can't do this because you need to provide jQuery with either DOM elements or event names.
You can bind events to new DOM elements manually or bind all possible events that can be in data-test-events (if you have 3-5 of them, with all DOM events it will become a silly and slow solution) and check if your element has one of them:
$('body').on("mouseover click mouseout mouseenter mouseleave", '.js-test', function(e) {
if (!$.inArray(e.type, $(this).data('test-events').split(' '))) {
return;
}
console.log("hello world!");
});​
If you want to trigger an event whenever a matching element is added to the DOM, you might want to have a look at livequery - http://docs.jquery.com/Plugins/livequery.
This code will allow you to register multiple event handlers as a function array. It's tested and working. See this jsfiddle demo and test cases.
JavaScript:
$(document).ready(function() {
eventFnArray = [];
eventFnArray["click"] = function(e) {
if(e.type != "click") return ;
alert("click event fired - do xyz here");
// do xyz
};
eventFnArray["mouseover"] = function(e) {
if(e.type != "mouseover") return ;
alert("mouseover fired - do abc here");
// do abc
};
eventFnArray["mouseout"] = function(e) {
if(e.type != "mouseout") return ;
alert("mouseout fired - do JKL here");
// do JKL
};
$('.js-test').each( (function(fn) {
return function(i) {
if(i != 0) return;
var _that = this;
var events = [];
events = $(_that).attr("data-events").split(" ");
// alert($(_that).attr("data-events") + " : " + events.join(" "));
$(this).parent().on(
events.join(" "),
'.js-test',
function() {
console.info("hello - this is the " + event.type + " event");
// alert("data-events = " + $(this).attr("data-events") + " : event.type = " + event.type);
// delegate to the correct event handler based on the event type
if($(this).attr("data-events").indexOf(event.type) != -1)
fn[ event.type ](event);
}
);
}
})(eventFnArray)); // pass function array into closure
});
HTML:
<div id="container">
Test 1
Test 2
</div>
Testing adding more elements:
Here are 3 test cases:
// adds a link with the click event attached.
$('#container').append("<a href='#' class='js-test' data-events='click'>TEst333</a>");
// adds a link with the mouseover event
$('#container').append("<a href='#' class='js-test' data-events='mouseover'>TEst444</a>");
// adds a link with mouseout
$('#container').append("<a href='#' class='js-test' data-events='mouseout'>TEs555</a>");
// adds a link with both mouseover and mouseout attached
$('#container').append("<a href='#' class='js-test' data-events='mouseout mouseover'>TEstLast</a>");
// mouseout and click
$('#container').append("<a href='#' class='js-test' data-events='mouseout click'>TEstLastForREAL</a>");
Word of caution:
I noticed that one of your links has both the click and mouseover attached. While this code will handle multiple events per link, as demonstrated by the last test case, the click event will not fire if a mouseover event is present.
This is not a fault in the above code but in the way events are processed, as demonstrated here:
// mouseover and mouseout fire, but not the click event
$('#container').on('mouseover mouseout click', '.js-test',function() { alert("afdas " + event.type); });

Can I determine what event triggered an event handler in jQuery if I bind multiple ones?

Check this example:
$('button').bind('click focus', function() {
// Did I click or focus?
});
Is there a way to work that out when binding multiple events to one handler?
This may work, but it is kind of ugly:
var eventType;
$('button').click(function() {
eventType = 'click';
do();
});
$('button').focus(function() {
eventType = 'focus';
do();
});
function do() {
alert(eventType);
}
You can use event.type on the event object (the first param passed to the handler), like this:
$('button').bind('click focus', function(e) {
if(e.type == "click") {
//do something, it was a click
}
});

How to stop onclick event in div from propagating to the document?

I want to stop propagation of this div's onclick event to the document? When the user click on the "div", both alerts appear: 1) the div's alert and 2) the document's alert. I want to suppress the document alert.
I know how to do it using addEventListener, but is there another way to to do it? The problem below is that I don't know how to get ahold of the event -- I tried "event = element.onclick", shown below, but that doesn't work. How do I get the event?
<head>
<script>
function showMenu(element) {
alert("div clicked");
event = element.onclick; // HOW TO GET HOLD OF THE EVENT?
// Don't propogate the event to the document
if (event.stopPropagation) {
event.stopPropagation(); // W3C model
} else {
event.cancelBubble = true; // IE model
}
}
document.onclick = function() {
alert('document clicked');
};
</script>
</head>
<body>
<div id="foodmenu" onclick="showMenu(this);">Click inside this div</div>
or click outside the div.
</body>
Change your function definition to include the event:
function showMenu(event, element) {
alert("div clicked");
// Don't propogate the event to the document
if (event.stopPropagation) {
event.stopPropagation(); // W3C model
} else {
event.cancelBubble = true; // IE model
}
}
Then change the call to pass in the event:
div id="fooddmenu" onclick="showMenu(event, this);">Click inside this div</div>
Try EventListeners:
html:
<div id="fooddmenu">Click inside this div</div>or click outside the div.​​​​​​​​​​
js:
function showMenu(e) {
alert("div clicked");
}
document.onclick = function() {
alert('document clicked');
};
window.onload = function(){
document.getElementById("fooddmenu").addEventListener("click", function(e){
showMenu(this);
e.stopPropagation();
});
};
Add the onclick to the body element.
Douglas,
It does stop the event from getting bubbled up.
Check this out http://jsbin.com/ahoyi/edit
here, if you comment the alert statement, it will show 2 alerts on clicking the smaller box else only one.
Hope this helps.
well, that's a jquery code.
$("#id") same as document.getElementById("id")
.click function is same as addEvent("click", function() { ... } );
so basically both the functions there are click handlers for Parent and Child DIVs.
Observe the output by commenting / uncommenting the "return false;" statement.
Hope that helps.
By the way, sorry for that "$" confusion.
$("div").click(function(){
...
...
...
return false; //this will stop the further propagation of the event
});
Add Pointer-events: none to the particular element will help to stop pointer events.
event.StopPropagation() will help us to avoid child propagating

Categories

Resources