trying to append content to DOM element - javascript

I'm trying to add a div to a row of content with the click of a button. My code works for the first row but not for any other row. Please help. This is the function for the button:
$(".addMMbtn").each(function() {
$(this).bind("click",
function() {
var thisRow = $(this).closest(".txtContentRow");
var thisTxt = thisRow.find(".txtContent");
var cellStr = '<div class = "mmCell prep"></div>';
$(cellStr).appendTo(thisTxt);
}
);
});
You can see a fiddle of the problem here: http://jsfiddle.net/z7uuJ/

$(".addMMbtn") will only find the elements present on the page and your code will only attach click event handler on them. Since you are adding the elements dynamically you should either use delegate or on (if you are using jQuery 1.7+) for click event to work on them too. Try this
Using delegate
$('#default').delegate('.addMMbtn', 'click', function() {
$('<div class = "mmCell prep"></div>')
.appendTo($(this).closest(".txtContentRow").find(".txtContent"));
});
Using on
$('#default').on('click', '.addMMbtn', function() {
$('<div class = "mmCell prep"></div>')
.appendTo($(this).closest(".txtContentRow").find(".txtContent"));
});
Demo

Instead of assigning click event directly on the button you need to use on():
$(document).on("click", ".addMMbtn",
function() {
var thisRow = $(this).closest(".txtContentRow");
var thisTxt = thisRow.find(".txtContent");
var cellStr = '<div class = "mmCell prep"></div>';
$(cellStr).appendTo(thisTxt);
}
);
In this case event handler will be subscribed to all newly added elements.
Code: http://jsfiddle.net/z7uuJ/5/

You don't need to loop through the elements to bind the handler:
$(".addMMbtn").live('click', function() {
var thisRow = $(this).closest(".txtContentRow");
var thisTxt = thisRow.find(".txtContent");
var cellStr = '<div class = "mmCell prep"></div>';
$(cellStr).appendTo(thisTxt);
});

Related

Attaching Right Click Event on Dynamically Created Elements

Below is the code that dynamically creates an element and attach an onclick event.
var div = document.createElement('div');
div.onclick = function(e){
console.debug(e);
}
var parent = document.getElementsByClassName('myid_templates_editor_center_menu');
parent[0].appendChild(div);
How about attaching a right click event?
The answer to your question consists of two parts:
1) How to attach the right-click event?
Answer: use the contextmenu event.
2) How to attach an event to dynamically created elements?
Answer: the idea is to attach the event to the parent element that will contain your newly created element. The event will propagate along the DOM until it reaches your parent element.
Working Example:
//get parent elements
var elements = getElementsByClassName('myid_templates_editor_center_menu');
//attach to the first found parent element
elements[0].addEventlistener('contextmenu', function(e) {
console.log("right clicked!");
})
Add
div.oncontextmenu = function(e){
e.preventDefault();
console.debug(e);
}
instead onclick
You can use contextmenu event
window.onload = function() {
var div = document.createElement("div");
div.innerHTML = "right click";
div.oncontextmenu = function(e) {
console.debug(e.type, e);
}
document.body.appendChild(div);
}
Working Example
node.addEventListener('contextmenu', function(ev) {
ev.preventDefault();
alert('success! - Right Click');
return false;
}, false);
Codepen :
http://codepen.io/mastersmind/pen/WogoVB
var div = document.createElement('div');
div.oncontextmenu = function(e){
console.debug(e);
}
var parent = document.getElementsByClassName('myid_templates_editor_center_menu');
parent[0].appendChild(div);

Jquery off event from a single element

I'm trying too take off the event from only this element , if I try $(this).off('event'); they take off event from all elements and $(this).off('click'); don't work
$(document).on('click', '.text', function (event) {
var box = "<div class = 'box'></div>";
$(box).insertAfter("#body");
$(this).off('event');
});
Try:
$(document).on('click', '.text', myEventHandler);
function myEventHandler(e){
$(this).off('click', myEventHandler);
var box = "<div class = 'box'></div>";
$(box).insertAfter("#body");
}

Jquery .on click event - removing the bound element

I have the following code:
$("#content h1").on("click", function(){
var f = $(this);
var clicked_id = f.data("id");
var children = _.filter(data, function(key){
var id = key.id.split("-")
id.pop()
id = id.join("-")
return clicked_id == id;
});
if (children.length != 0) {
$("#content").html("");
_.each(children, function(obj){
$("#content").append("<h1 data-id='"+ obj.id +"'>"+ obj.txt +"</h1>")
});
}
});
So basicly Im binding a .on "click" event to h1. On the click I clean the element containing the H1 then I add a new H1 element. Now the click does not register anymore. How should I actually be doing this so I can keep clicking?
Use on like so (event delegation):
$("#content").on("click", "h1", function() {
Now, each time you click #content, it'll check for an h1 and run the event. Your previous code only bound the handler to the h1 at runtime.
Maybe you could bind this way?
$(document).on("click", "#content h1", function(){
...
});

Assign click-event on a new element in the event itself

I want to create a new element and assign this element the same event for onclick, which it has created it.
DEMO
$(function(){
var counter = 0;
$('.sub').click(function(event){
event.stopPropagation();
counter++;
$div = $(this); // makes more sense in the original code
$div.append('<div class="sub" title="subsub">subsub' + counter + '</div>');
//$div.find('.sub').click // <-- ?????
});
});
In my demo I want to create a new subsub for every sub, which was clicked. Than I want to add the same click event to the new subsub element.
Could anyone help me with this?
I've found nothing for this problem. Maybe I don't have the correct keywords for google or SO :/
Just use event Delegation
$(document).on('click', '.sub', function(event){
Your click events seem to be working correctly at this point,because you are using append which actually nests the new div inside the div that is clicked. Try using after and the functionality breaks.
$(function(){
var counter = 0;
$(document).on('click', '.sub', function(event){
event.stopPropagation();
counter++;
$div = $(this); // makes more sense in the original code
$div.after('<div class="sub" title="subsub">subsub' + counter + '</div>');
});
});
Check Fiddle
Why not create proper elements instead :
$(function(){
var counter = 0;
$('.sub').on('click', doStuff);
function doStuff(event) {
event.stopPropagation();
counter++;
var $div = $(this),
$sub = $('<div />', {'class':'sub',
title : 'subsub',
text : 'subsub' + counter,
on : {
click : doStuff
}
}
);
$div.append($sub);
}
});

jQuery Bind each() and also click() on the same function

So I have the following fragment:
$(".server").each(function() {
var element = $(this);
//bunch of javascript here with element
});
I also want to bind a single click event for an id to do the same work as the above, how is this possible, without copying and pasting the entire block and doing:
$("#my-id").click(function() {
var element = $(this);
//bunch of javascript here with element
});
I think the following should work:
var eventHandler = function() {
var element = $(this);
//bunch of javascript here with element
};
$(".server").each(eventHandler);
$("#my-id").click(eventHandler);

Categories