Adding an Event via jQuery to newly created DOM Element - javascript

I am trying to assign an event to a newly created DOM Element:
var Element = document.createElement("div");
$(document).on('click',Element,function() {
console.log("B");
});
After executing this code and clicking on the newly created div, nothing happens.
Any idea why?
I have also tried:
var Element = document.createElement("div");
$(Element).click(function(event) {
console.log("B");
});

You need to add the element to the DOM before it will receive events.
Here's one way to do it:
var $div = $('<div>')
.text('Click Me!')
.on('click', function() {
alert('Clicked!');
});
$(document.body).append($div);
// Now you can click on it and see the alert.

Since you're using jQuery...
var Element = $("<div/>").click(function() {console.log("B");}).appendTo('body');
Of course, append it where you need it...

Just bind your event on the body and pass your selector in parameter like this:
$('body').on('click','.foo',function() {
console.log("B");
});
var Element = document.createElement("div").className = "foo";
Here the codepen :
http://codepen.io/anon/pen/xvLqo

Related

How can we pass an element to event handler in javascript

I have created an <input> HTML element using Javascript. Now I want to add an onblur event handler to this element dynamically. However I do not understand how I can pass the created element as an argument to the function. Here's my code:
element = document.createElement("input");
element.onblur = hello_function;
In the above code you can see that the element is created. Now I want to pass that element to hello_function. How can I do that?
function hello_function(element) {
alert(element);
}
To achieve this you can wrap the hello_function call in an anonymous function wrapper and provide the this argument:
element = document.createElement("input");
element.addEventListener('blur', function() {
hello_function(this);
});
document.body.appendChild(element);
function hello_function(element) {
console.log(element);
}
Also note the preferred use of addEventListener over onblur.
try like this. passing the another variable into a function,
var something="hello";
var element = document.createElement("input");
element.addEventListener('blur' , function ()
{
hello_function(something);
})
document.body.appendChild(element)
function hello_function (element){
alert(element);
}
i suggest to use addEventListener, also i think you need to append the created element to the document, something like this:
var elem = document.createElement("input");
if (elem) {
elem.addEventListener('blur', hello_function, false);
}
document.body.append(elem);
function hello_function(element) {
alert(element);
}

Can't get cloned element to keep originals events

I'm trying to clone an element that is passed into a function and all events associated to it, as there are $('.example').on('click', function(e) ... )} events like this defined in document ready.
So I do following:
$('.example').on('click', function(e) {
e.preventDefault();
surpriseMe($(this));
});
and I try to clone this element along side its events here (I need to grab parent as .html() returns only inner html, hence element itself) :
function surpriseMe(element) {
var newElement = element.parent().clone(true,true).html();
surprise.insertBefore(element.parent());
if (numElements == 3) {
newMonth = $('<li class="item-dragable-placeholder">'+ newElement +'</li>
}
}
I believe true, true inside .clone() should force parent also grab its children events, but whenever I click on newly placed element, nothing happens
To use event delegation...
Change:
$('.example').on('click', function(e) { ...
To:
$(document).on('click', '.example', function(e) { ...
Note: Instead of using document, find the closest ancestor element (container) that's available on page load and use that.
when you do your insert, instead of inserting the new element, you ask to insert only the html, remove the html part, it will give you the element and its functionalities.
var newElement = element.parent().clone(true,true).html();
See the following (example)[http://jsfiddle.net/dshun/1j9khfnc/4/](please note, since the example code given is not complete. For example, the variable surprise, numElements are not declared. I made some assumptions in my fiddle)
$(document).ready(function(){
var numElements=0;
function surpriseMe(element) {
var newElement = element.parent().clone(true,true);
newElement.insertBefore( ".inner" );
numElements++;
if (numElements == 3) {
newMonth = $('li.item-dragable-placeholder').insert(newElement);
}
}
$('.example').on('click', function(e) {
e.preventDefault();
surpriseMe($(this));
});
});

jQuery Move div into another div

I need to move .link-field-first-ticket-button inside .event-location-one
here's the fiddle: http://jsfiddle.net/ksV73/
It's a cms so I have no choice in the matter.
this is what I'm trying, it's not doing much of anything
$(".widget-upcoming-events-blog li").each( function() {
var links = $(this).children(".link-field-first-ticket-button").html();
$(this).children(".link-field-first-ticket-button").html("");
$(this).children(".event-location-one").append(links);
});
You can just do this:
$(".link-field-first-ticket-button").appendTo(".event-location-one");
It will move the first ticket button to event location
x = $(".widget-upcoming-events-blog").find(".link-field-first-ticket-button").remove()
$(".event-location-one").append(x);
The html method will give you the content inside the element, not the element itself.
Just append the element where you want it. As an element can't exist in two places at once, it will be moved:
$(".widget-upcoming-events-blog li").each( function() {
var links = $(this).children(".link-field-first-ticket-button");
$(this).children(".event-location-one").append(links);
});
try this
$(".widget-upcoming-events-blog li").each( function() {
var links = $(".link-field-first-ticket-button").html();
$(".link-field-first-ticket-button").html("");
$(".event-location-one").append(links);
});
Change your .children() to .find()
$(".widget-upcoming-events-blog li").each( function() {
var links = $(this).find(".link-field-first-ticket-button").html();
$(this).find(".link-field-first-ticket-button").html("");
$(this).find(".event-location-one").append(links);
});
How about use the .appendTo() function?
For example:
$(".widget-upcoming-events-blog li").each( function() {
$(this).find(".link-field-first-ticket-button")
.appendTo( $(this).find(".event-location-one") );
});

Get value of dom element in ready function

I want my textArea to resize when the page is fully loaded. I found that
$(document).ready(function() {
// Handler for .ready() called.
});
can help me, so I try to test it and put next code into that function:
$(document).ready(function() {
var element = $('#elementId');
alert(element.value);
});
But when the page is loading, alert shows undefined value of textArea, however there is text inside it.
How can I fetch those value inside ready function?
$(document).ready(function() {
var element = $('#elementId');
alert(element.val());
});
element isn't a DOM element but a jQuery wrapped object, it doesn't have any value property.
Use
$(document).ready(function() {
var element = $('#elementId');
alert(element.val());
});
or
$(document).ready(function() {
var element = document.getElementById('elementId');
alert(element.value);
});
or
$(document).ready(function() {
var element = $('#elementId');
alert(element.get(0).value);
});
You need to use DOM object to use value property and you have jQuery object you need to use val() on it.
$(document).ready(function() {
var element = $('#elementId');
alert(element[0].value);
//or
alert(element.val());
});

Is there an easier way to reference the source element for an event?

I'm new to the whole JavaScript and jQuery coding but I'm currently doing this is my HTML:
<a id="tog_table0"
href="javascript:toggle_table('#tog_table0', '#hideable_table0');">show</a>
And then I have some slightly ponderous code to tweak the element:
function toggle_table(button_id, table_id) {
// Find the elements we need
var table = $(table_id);
var button = $(button_id);
// Toggle the table
table.slideToggle("slow", function () {
if ($(this).is(":hidden"))
{
button.text("show");
} else {
button.text("hide");
}
});
}
I'm mainly wondering if there is a neater way to reference the source element rather than having to pass two IDs down to my function?
Use 'this' inside the event. Typically in jQuery this refers to the element that invoked the handler.
Also try and avoid inline script event handlers in tags. it is better to hook those events up in document ready.
NB The code below assumes the element invoking the handler (the link) is inside the table so it can traverse to it using closest. This may not be the case and you may need to use one of the other traversing options depending on your markup.
$(function(){
$('#tog_table0').click( toggle_table )
});
function toggle_table() {
//this refers to the element clicked
var $el = $(this);
// get the table - assuming the element is inside the table
var $table = $el.closest('table');
// Toggle the table
$table.slideToggle("slow", function () {
$el.is(":hidden") ? $el.text("show") : $el.text("hide");
}
}
You can do this:
show
and change your javascript to this:
$('a.tableHider').click(function() {
var table = $(this.name); // this refers to the link which was clicked
var button = $(this);
table.slideToggle("slow", function() {
if ($(this).is(':hidden')) { // this refers to the element being animated
button.html('show');
}
else {
button.html('hide');
}
});
return false;
});
edit: changed script to use the name attribute and added a return false to the click handler.
I'm sure this doesn't answer your question, but there's a nifty plugin for expanding table rows, might be useful to check it out:
http://www.jankoatwarpspeed.com/post/2009/07/20/Expand-table-rows-with-jQuery-jExpand-plugin.aspx

Categories

Resources