Binding events to table cells using jQuery - javascript

This is my markup:
<div id="divContainer">
<div>
<table></table>
</div>
<div>
<table></table>
</div>
....
</div>
I need to to register mouseenter event on all tds of all the tables (that are present inside each div).
$(document).ready(function () {
$allTds = $('#divContainer').find("tr").find("td");
...
SomeFunction();
});
function SomeFunction(){
$allTds.on({
mouseenter: function (e) {
alert('hover');
}
});
}
But I don't get any alerts.

They way you apply the event listener is weird.
$('#divContainer').on('mouseenter','td',function() {
alert('mouse entered');
});
Also: It's good that you cache the td elements, but why don't you stick with something more simple?
$allTd = $('#divContainer td');

The reason your event handlers aren't being bound is that the <td> elements don't exist when you enter the document ready handler.
You should use event delegation for this. For example
window.jQuery(function($) {
$('#divContainer').on({
mouseenter: function(e) {
alert('hover');
}
}, 'td');
});
This way, it's the #divContainer element that listens for the events and acts on them if they originate from a <td>.
See http://api.jquery.com/on/#direct-and-delegated-events
You also had a scoping problem where the $allTds variable is only defined in the document ready handler and is not in scope of the SomeFunction function.

Related

JS: append cannot find attr

$(".btn").click(function()
{
$(".content").append(
"<div class='randomDiv' id='1'></div>"
);
}
If above is "active" then I cannot:
$(".randomDiv").click(function()
{
alert($(this.attr("id")));
}
I've googled and found out that it is because JS is loaded before I append, but haven't found a solution how to "register after load" on JS.
Either:
Attach the event handler when you create the element
$(".btn").click(function() {
$("<div class='randomDiv' id='1'></div>")
.on("click", myFunction)
.appendTo(".content");
}
function myFunction() {
alert($(this.attr("id")));
}
… so the element does exist when you bind the event handler
Use a delegated handler
$(document).on("click", ".randomDiv", function () {
alert($(this.attr("id")));
});
… that captures all the click events as they bubble up the document and checks which elements they came from.
$(".content").on('click', '.randomDiv', function()
{
alert($(this.attr("id")));
}
$(".content") can be replaced with any existing parent item of randomDiv. Say content div is inside page-left div then above code can be written as
$(".page-left").on('click', '.randomDiv', function()
{
alert($(this.attr("id")));
}
Or even
$(document).on('click', '.randomDiv', function()
{
alert($(this.attr("id")));
}
which bind event to the document level in DOM
Depending upon the version of jQuery you should use live, delegate, bind or on function.
If you append the element dynamically then the normal click function wont work. Use
$(document).on("click",".randomDiv",function(event){
alert($(this).attr("id"));
});

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"/>

How to setup Rx.Observable.fromEvent to work with jQuery filtered events

There are lots of examples of Rx.Observable.fromEvent(element, eventName) using a jquery selection as the element to capture events from. However is it possible for Rx listen to only events from a filtered event setup with jQuery?
//Bind the event on body but only respond to events that match the filter
$('body').on('click', '.aClass div .something', function () {...});
//Bind to 'body' but only respond to events from the binding above
Rx.Observable.fromEvent(/*something here?*/);
I have come up with something effectively similar but it seems like it would be much more costly than the jquery filter.
Rx.Observable.fromEvent($('body'), 'click')
.filter(function (e) {
return $(e.target).is('.aClass div .something');
})
.subscribe(function () {...});
Is there some way I could turn the jQuery binding into an emitter and use that event stream with Rx?
What's the best approach?
see http://jsfiddle.net/ktzk1bh3/2/
HTML:
<div class="aClass">
<div>
<a class="something">Click me</a>
</div>
</div>
Javascript:
//Bind to 'body' but only respond to events from the binding above
var source = Rx.Observable.create(function(o) {
$('body').on('click', '.aClass div .something', function(ev) {
o.onNext(ev);
})
});
var sub = source.subscribe(function(ev) { console.log("click", ev) });
You can use Rx.Observable.fromEventPattern.
Rx.Observable.fromEventPattern(
function add(handler) {
$('body').on('click', '.aClass div .something', handler);
},
function remove(handler) {
$('body').off('click', '.aClass div .something', handler);
}
);
This way it will automatically remove event handler on unsubscribe from observable subscription.
<div class='radios'>
<input type='radio' name='r' value='PM'>PM
<input type='radio' name='r' value='PCE'>PCE
<input type='radio' name='r' value='PCS'>PCS
</div>
<textarea class='textarea'>
</textarea>
Rx.Observable.fromEvent(document.querySelector('.radios'),'click')
.subscribe((e)=>console.log(e.target.value));

Getting element id with jquery

The code should print the id of the selected div but it does not. I did not find the error. Thanks for help.
HTML
<body>
<div id="form_area">
<div>
<button onclick="return add_row();" style="width:100%;">Add Row</button>
</div>
</div>
</body>
Javascript
$(document).ready(function() {
$('#form_area div').click(function(e) {
console.log($(this).attr('id'));
});
});
function add_row() {
var random_id = Math.floor((Math.random() * 1000) + 1);
$('#form_area').prepend('<div id="' + random_id + '" class="form_row"></div>');
}
Ok, I think I understand what you are missing. You are trying to log the ID after adding a row using add_row function,
.form_row is added dynamically to the DOM. So when executing $('.form_row').click(, there is no .form_row to bind the handler. The below way of using .on method binds the handler to #form_area and executes the handler only when the click event is from .form_row
$('#form_area').on('click', '.form_row', function () {
console.log(this.id);
});
$('#form_area div') selects the div inside the div #form_area which doesn't have an ID
Below comment in html shows which div is selected,
<div id="form_area">
<div> <!-- $('#form_area div') selects this div-->
<button onclick="return add_row();" style="width:100%;">Add Row</button>
</div>
</div>
To access id use 'on' as your div is dynamically generated:
$(document).ready(function() {
$('#form_area').on('click', '.form_row', function () {
console.log(this.id);
});
});
Try console.log($('#form_area div').attr('id'));
Firstly, you have jQuery - you should use that to register your event handlers instead of using obsolete, error prone inline event handlers.
Secondly, your button handler is inside #formarea and so is also triggering the click handler since the button's parent has no ID. This is probably not desired.
Thirdly, your event handlers need to be delegated because you're trying to catch events on dynamically added elements.
So, remove the onclick attribute and add this:
$('#formarea button').on('click', addRow);
$('#formarea').on('click', '.form_row', function() { // delegated, for dynamic rows
console.log(this.id); // NB: not $(this).attr('id') !!
});
function addRow(ev) {
// unmodified
}
See http://jsfiddle.net/alnitak/aZTbA/

$(document).ready listeners not running on dynamic content

I have a $(document).ready function that sets up listeners for certain elements. However, all of the #leave-ride elements are added dynamically.
Listeners:
$(document).ready(function() {
$("#post-ride").click(function() {
addRide(currentDriver, $(destinationInput).val(), $(originInput).val(), $(dateInput).val(), $(timeInput).val());
$.getScript("scripts/myRides.js", function() {});
});
$("#request-ride").click(function() {
requestRide(currentDriver, $(destinationInput).val(), $(originInput).val(), $(dateInput).val(), $(timeInput).val());
$.getScript("scripts/myRides.js", function() {});
});
$("#leave-ride").click(function() {
console.log("leave Ride");
leaveRide(currentDriver, $("leave-ride").closest("div").attr("id"));
$.getScript("scripts/myRides.js", function() {});
});
});
What do I need to do to get that listener to listen to dynamic content?
Yes, ready runs only once. You can use event delegation:
Take the element closest to the #leave-ride which is not loaded dynamically (document in extreme cases). Then attach the handler on it, and use #leave-ride as the selector for the delegated event.
Assuming a div having the id #container is that static element:
$('div#container').on('click', '#leave-ride', function(){…});
See also Event binding on dynamically created elements?
Use on, change your event declaration
$("#post-ride").click(function() {
to
$("body").on('click',"#post-ride",(function() {
Use .on()
Example:
$("#leave-ride").on('click', function() {
console.log("leave Ride");
leaveRide(currentDriver, $("leave-ride").closest("div").attr("id"));
$.getScript("scripts/myRides.js", function() {
});
});

Categories