Get selector in Jquery delegate event handler - javascript

I have the following code
Here i have 2 selectors "td.slot" and "td.slot1" and 2 events "mouseover" and "mouseleave".
As you can see i am using e.type to get one of the events. Now i want to know if there is a way like e.selector where i can get one of the selectors
$(document).ready(function(){
$("table").delegate('td.slot,td.slot1','mouseover mouseleave',function(e){
var row = $(this).parent()[0];
var rowHead = row.cells[0];
var colHead = row.parentNode.rows[0].cells[$(this).index()];
if (e.type == 'mouseover') {
$(rowHead).css("background-color","orange");
$(colHead).css("background-color","orange");
}
else
{
$(rowHead).css("background-color","white");
$(colHead).css("background-color","white");
}
});

Description
You can use event.currentTarget
event.currentTarget The current DOM element within the event bubbling phase.
Sample
html
<body>
<div>div</div>
<button>button</button>
</body>
jQuery
$("body").delegate('div,button','click',function(e){
alert($(this));
});
Check out this jsFiddle
More Information:
jQuery- Event Object

Related

Not able to alert/access the changed id after cloning

My code is :
var draggedElement = this.template.querySelector("[id='"+divId+"']");
var cln = draggedElement.cloneNode(true,true);
cln.classList.add('completed');
cln.classList.add('box-height');
cln.id='clone-'+divId;
event.target.appendChild(cln);
Now if I want to alert the event target id on the onclick event it gives empty result.
Trying to use like this but did not work.
const btn = this.template.querySelector("[id='clone-"+divId+"']");
btn.addEventListener('click', function(event){
console.log('Button Clicked');
console.log(event.target.id);
});
Can anyone please help? Thanks in advance.
You are probably binding the event handler before the dragged element is created (which I suppose is done in response of a user action).
Instead of playing with id attributes, just bind the event handler at the moment you add the cloned element to the document. At that time you have the reference to the cloned element, so you can just add the event listener to it.
Little, simplified, demo:
var draggedElement = document.querySelector("#test");
var cln = draggedElement.cloneNode(true,true);
cln.removeAttribute("id"); // Don't use `id`
cln.textContent = "cloned " + cln.textContent;
document.body.appendChild(cln);
cln.addEventListener('click', function(event){
console.log('Cloned button Clicked');
});
<button id="test">test</button>
Event Delegation
Although I would strongly advise against using dynamically generated id attributes, if you really require to identify elements by such id attributes, then use event delegation:
setTimeout(function () { // In reality this would be some drag event handler
var draggedElement = document.querySelector("#test");
var cln = draggedElement.cloneNode(true,true);
cln.id = "cloned-" + cln.id; // Bad practice
cln.textContent = "cloned " + cln.textContent;
document.body.appendChild(cln);
}, 500);
// Event delegation
document.body.addEventListener('click', function(event){
if (event.target.id = "cloned-test") {
console.log('Cloned button Clicked');
}
});
<button id="test">test</button>

jquery (hover and load) events binding on dynamically created elements

I am able to bind click event to element with class name keybox. And this element is generated dynamically.
$('body').on('click','.keybox', function(){
// some code here
});
But for same element I tried binding hover and load event using following code:
$('body').on('hover','.keybox', function(){
// some code here
});
$('body').on('load','.keybox', function(){
// some code here
});
....and its not working as expected.
Can someone help with this problem? I want to bind hover and load event to my element with class name keybox and this element is generated dynamically.
Instead of hover, use mouseenter and mouseleave event. Instead of body.load use
$(document).ready(function() {
You can use following approach to bind multiple events and get object information via event object.
$('body').bind('click hover load', '.keybox', function(e){
if ( e.type === 'hover') {
// do something
}
else if(e.type === 'click') {
// do something
}
....
});
Make sure you bind events in $(document).ready(function() {} or load javascript just in bottom of html document body.
Since hover is deprecated you should use mouseenter and mouseleave for load you can write using event using on(load is equivalent to ready).
$(function(){
$(document).on('mouseenter', '.keybox', function () {
$(this).css('color','red');
});
$(document).on('mouseleave', '.keybox', function () {
$(this).css('color','black');
});
$(document).on('click', '.keybox', function () {// click on dynamically loaded events.
$(this).css('color','green');
});
$('#btn').click(function() {
$('#parent').append("<div class='keybox'>sample1</div>");
$('#parent').append("<div class='keybox'>sample2</div>");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent">
zdhsdhsau
</div>
<input type="button" id="btn" value="create"/>

JS event listener for a type of element?

Is there a way to add some kind of listener for a type of html element? For example if i wanna call a function when the user clicks any p element
the easiest answer would be using addEventListener() if you want a specific html tag just like what i wanted in my question then you'll find the answer there ill paraphrase it here too
add this
<script>
document.addEventListener("click", function(e){
//your desired nodeName like : DIV , SPAN , LI etc
if(e.target && e.target.nodeName== 'DIV')
//add a function below to trigger
{alert('bingo')}
});
</script>
to the end of your document
by the way don't forget to use uppercase nodeNames or just put a toLowerCase() before it. cheers :)
Add the event listener to the window / document / document.body and check the type of the element and the types of its parents because if you have a <span> inside a <p>, clicking the span won't trigger the click in the paragraph.
document.addEventListener("click", function (eventArgs) {
var target = eventArgs.target;
var elementToLookFor = "p";
while (target !== null) {
if (target.tagName.toLowerCase() === elementToLookFor) {
// Do magic stuff with the paragraph
console.log(target);
}
target = target.parentElement;
}
});
This technique is called "event delegation."
Edit: Note that you cannot early return from the loop above. If your have nested paragraphs, i.e.
<p>
Hey,
<p>there!</p>
</p>
Having an early return will only call your event handler for the inner paragraph, whereas you said that you'd like the handler to be invoked on every paragraph which is why you need to traverse all the ancestors of the element.
I assume that you are looking for code along these lines:
var paras = document.getElementsByTagName("p");
// Loop through elements.
for(var i = 0; i < paras.length; i++) {
// Add listener.
paras[i].addEventListener("click",
function() {
// Execute function.
}, false);
}
I'd just select all the elements on the page and add eventListeners on them like so:
function addListeners(elementType, eventType, callback) {
Array.prototype.slice.call(document.querySelectorAll(elementType)).forEach(function (el, i) {
el.addEventListener(eventType, callback, false);
});
}
Above we use querySelectorAll to pick all the wanted elements, convert it to an Array (if you use es6, you can use Array.from) and then we loop through the array and add listeners with the wanted callback.
Here's an example: https://jsfiddle.net/a7en4d4s/
Look at this JSFiddle, and see if it works for you
<span>Click Yes</span><br/><br/>
<span>Click No</span><br/><br/>
<a>Clicked: <b id="result"></b></a>
<script>
$("span").click(function(){
var a = $(this).html();
$("#result").html(a);
});
</script>

How detect any of all events using jquery?

I have function to detect idle state of user. I want to update database if any of the event occurs.Now i have script like this
$("body").mousemove(function(event) {
myfuction();
});
I want to convert above script like this
$("body").anyOfTheEvent(function(event) {
myfuction();
});
How can i do this?
You can find the event name using the e.type property. Try looking this example
$('#element').bind('click dblclick mousedown mouseenter mouseleave',
function(e){
alert("EventName:"+e.type);
});
​
The jsfiddle for this is here http://jsfiddle.net/qp2PP/
You could have an array of the events you're interested in and subscribe to all of them
var events = ['click','mousemove','keydown'] // etc
$.each(events,function(i,e){
$('body')[e](myfuction);
});
Get a list of events here: http://api.jquery.com/category/events/
You can bind more than one event with bind()
$('#foo').bind('click mousemove', function(evt) {
console.log(evt.type);
});
just use on(), with a space-delimited list of events:
$('body').on('mousedown click', function(e) {
var eventType = e.type;
// do stuff
});
References:
on().
Instead of bind to specific element, you can bind directly to document.
$(document).bind('click mousemove', function(evt) {
document.getElementById("demo").innerHTML = Math.random();
});
Example in CODEPEN

Which HTML element was Double Clicked in the DOM

I would like to detect which HTML element was double clicked. Seems to something not fire in my code. Following is my HTML code structure where you double click detect which item is clicked.
<div id="mainWrapper">
<div id="Banner" name="Banner" class="editable">This is the banner</div>
<div id="MainMenu" class="editable">This is the main menu</div>
<div id="LeftSideBar" class="editable">This is the submenu or left sidebar content</div>
<div id="MainContent"class="editable">Here is the main content</div>
<div id="RightSideBar" class="editable">Here are commercial ads</div>
<div id="Footer"class="editable">This is the footer
Go Home
</div>
</div>
External JavaScript
window.onload = function(){
// Listen to the double click event.
if ( window.addEventListener )
document.body.addEventListener( 'dblclick', onDoubleClick, false );
}
Get the element which fired the event. This is not necessarily the element to which the event has been attached.
function onDoubleClick( ev ){
var element = ev.target || ev.srcElement; //target = W3C, srcElement = Microsoft
alert(ev.type); //displays which event has fired
var targ;
if (!ev) var e = window.event;
if (ev.target) targ = ev.target;
else if (ev.srcElement) targ = ev.srcElement;
alert(ev.target); //displays which type of html element has been clicked (it shows div but not which div)
// Find out the div that holds this element.
var name;
do {
element = element.parentNode;
}
while ( element && ( name = element.nodeName.toLowerCase() ) && ( name != 'div' ||
element.className.indexOf( 'editable' ) == -1 ) && name != 'body' )
alert("The class name for the element is " + element.className); // I get nothing
alert("The node name for the html element is " + element.nodeName);// I get "body"
}
I'm not sure exactly what it is you're trying to accomplish. Is it so people can edit things? I'd be tempted to apply the onclick event listener just to those items you want to be editable. If they all have "editable" css classes, doing so is trivial with jquery:
$('.editable').dblclick(dblclickFunc)
This would apply an event listener to every element with a class of editable. However, to make it more useful, I'd change that to
$('.editable').dblclick(function(e){ dblclickFunc(e, this); })
and for the function
dblclickFunc(e, el){
alert('received an event of type ' + e.type + ' on ' + el.tagName);
}
So you've got a reference to the element that sent the event. From there, you could check IDs, or even go so far as to loop through all your editable elements and compare them to the one that got passed to you. Once you have a match, you know precisely which element was clicked on.
You are using JavaScript in your example, but you also tagged the question with jQuery, so I assume jQuery is OK to use. In fact, exactly this type of event handling is greatly simplified using jQuery’s API, since it normalizes the events for all modern browsers. Highly recommended.
You can delegate the event to the document and detect all double clicks in the entire document using jQuery using the on() function:
$(document).on('dblclick', function(e) {
console.log(e.target); // target is the element that triggered the event
alert("The class name for the element is " + e.target.className);
alert("The node name for the html element is " + e.target.nodeName);
});
If you want to listen on certain elements inside a specific container, try this:
$('#mainwrapper').on('dblclick', 'div', function(e) {
console.log(e.target);
});
This will listen for any double clicks inside #mainwrapper, but only trigger the handler if a DIV element was the target.
You can use .on()
$(".editable").on("dblclick", function(e){
$(this).attr('class') //Class Name
});

Categories