Adding jQuery UI slider to dynamically generated element? - javascript

So I'm adding list elements to a list using .append(). Within the appended element is a div I need to attach the jQuery Slider widget to. Not sure if I have to use .on() or something. FWIW, an unlimited amount of li's can be added, which is why I'm using a class for the div.
Anyway here's a simplified snippet:
$('.cycleDuration').slider();
$cycleBlock += '<li>';
$cycleBlock += '<div class="cycleDuration"></div>';
$cycleBlock += '</li>';
$('#cycles').append($cycleBlock);

You will need to bind the code before the element is actually appended I think. In this example I just bound a click event because I don't have your slider code.
http://jsfiddle.net/4vwUd/1
$('button').click( function() {
//turn your div into a jquery object
var $cycleBlock = $('<div class="cycleDuration"></div>');
//bind the event
$cycleBlock.bind('click', function() { alert(); });
//append to the list
$('#cycles').append('<li />').children('li:last').append($cycleBlock);
});

simply u can re-call " $('.cycleDuration').slider(); " after every appends the list elements, that will bound added class elements to that function.

Related

how to select a div from multiple div on jquery click event if all div have same class?

I have a div with a class .display_noti and inside it I have append another div with class .palnotific by jquery.I have fetched data from database and i converted that fetched data into json_encode.I used that json format data and made some information which were append on that div with class .palnotific.
my first jquery code which append data inside that div with class .display_noti looks like :-
$.getJSON("notification.php",function(data){
// you can do checking here
if ( data.result && data.result.length > 0 ) {
$(".display_noti").empty(); // Clear out the div
$.each(data.result,function(){
$(".display_noti").append("<div class='palnotific'>You got a pal requet from <strong>"+this['from_user']+"</strong><br><span class='date'>"+this['notification_date']+"<form method='post'><input type='text' class='palid' value='"+this['pals_id']+"'></form></div>");
});
done();
}
else {
$(".display_noti").append("<div class='palnotific' style='background-color:white;'>You have no notification to view.</div>");
}
Above I first get the json format data and I did some validation and then at last I append that second div with class .palnotific inside that first div with a class .display_noti.I have a form inside that append div which I use to take value from a input for use.
As we know .palnotific is an appended div.I wanted to use some Onclick event function on it so, I used below code :-
$('body').on('click','.palnotific',function(){
var x = $(this).closest('.display_noti').find('.palid');
var pid=x.val();
$.ajax({
url:'notifipro.php',
type:'post',
data:"palid="+pid,
success: function(data){
if(data==1)
{
$(window).load('oldpage.php');
}
if(data==2)
{
$(window).load('newpage.php');
}
}
});
});
Above code takes the input value from that form which was inside that .palnotific div which was appended from jquery at previous.As you know those appended div carry data from database via json_encode.It will take value as much as available in database which mean if there's 2 data in database json_encode will also have 2 data and those append div class which takes data from json_encode will append 2 time that div with a class palnotific.Now my problem is that if i have two div with class palnotifi origin from that append my click function work for first div only and when i click on second div onclick function doesn't work.No matter I have 2 or more then two div if I click any one div first div click function takes action.How can I make work onclick function to those div only which have been clicked?
The easiest way to have jquery react on an element that is dynamically created, is to attach the event to that element itself. Another way would be using on on a the container div with a subfilter, but since you are already creating the html, you can encapsulate it in $('yourhtml') and attach the click directly to that created element. In combination with appendTo instead of append, you can also chain the append and click:
//mock data:
var data={result: [
{from_user: 'A', notification_date: new Date(), pals_id: 1},
{from_user: 'B', notification_date: new Date(), pals_id: 2},
{from_user: 'C', notification_date: new Date(), pals_id: 3}
]};
$.each(data.result,function(){
var id = this.pals_id;
$("<div class='palnotific'>You got a pal request from <strong>"+this['from_user']+"</strong><br><span class='date'>"+this['notification_date']+"<form method='post'><input type='text' class='palid' value='"+ id +"'></form></div>")
.appendTo(".display_noti")
.click(function(){
//attach pre existing function or assign your logic here
alert('You clicked ' + id);
})
});
Example fiddle
In this example, the id was also stored before hand and reused inside the attached click. If you need to use the raw value, you can use $(this).find('.palid').val() (as done in this fiddle )
From the code you paste, the problem should be this line:
var pid=x.val();
as you can find in jQuery docs (http://api.jquery.com/val/)
.val() Get the current value of the first element in the set of matched elements or set the value of every matched element.
You can use a more specific CSS3 Selector in the on() function. I'm not entirely sure this is going to solve your overall problem, but it might lead you in the right direction.
$(".display_noti").on("click", ".palnotific:first", function(event) {
console.log("You Clicked: ", event.target.id);
});
Here is an example JSFiddle;

jQuery Draggable not behaving as expected

My jQuery drag and drop environment in this fiddle is not behaving as expected: each initial div should be freely draggable and the 'adddiv' button will add another draggable div. They should not stop being draggable, they should be able to be dragged again not freeze in position.
I've used .draggable() to enable dragging and also report positioning to the console and .append() to add more divs.
Right now after the initial move, they freeze, but the appended divs can be moved again.
I fixed your issue.
You were creating a div with the same id '6' each time you clicked on add div.
$("#adddiv").click(function() {
$('<div></div>').draggable().appendTo($('#set'));
});
Fiddle : http://jsfiddle.net/vQ3Tg/1/
Assign the attribute values dynamically, like -
$("#adddiv").click(function() {
var lastid = $("#set div").last().attr('data-need')
lastid = parseInt(lastid) + 1;
$('#set').append('<div id="' + lastid+ '" data-need="' +lastid + '"></div>');
$( "#" + lastid ).draggable();
});
There may be more concise ways to do this. Still, this works on your jsFiddle http://jsfiddle.net/vQ3Tg/ , for more than 1 dynamically appended blocks, without freezing.
You have to use class instead of id. Demo Here.
$('#set').append('<div class="6" data-need="6"></div>');

Adding onclick events to appended div tags in JavaScript

I am trying to add a click event to a bunch of div elements that I created by appending them and I am having some trouble.
I have a bunch of div elements the with the ids a0 ---> an. I am trying to create a for loop after the divs are created to assign them click events. The issue is the way I am doing it when the click event happens I do not have any way to track which div fired the event. The code bellow might make that more clear. So the issue I am having is that #a + i always returns the last div, and I want it to return the div number that was clicked.
$(document).ready(function () {
traverse(oo);
for (i = 0; i <= groupNum; i += 1) {
$("#a" + i).click(function () {
console.log("#a" + i + "clicked");
});
}
});
I thought about returning a closeur, but that seems I would make it even more complicated. Does anybody have any advice on how to do this the best?
Thanks in advance.
I'm not sure what you are trying to do but if you just want to assign a click event to a bunch of elements then use the correct selector (note the use of $(this) to get the clicked element):
$("div").click(function(){
var clickedDiv = $(this);
var id = clickedDiv.attr("id");
});
If you don't want ALL div elements, then you could add a class to them and use a different selector:
$(".MyDivClass").click(function(){...
or without the class, a 'starts with' on the id (the following with get all div elements where the id attribute starts with "a"):
$("div[id^='a']").click(function(){...
If you are dynamically adding divs with other javascript and you want them to automatically have the click events, use the on function...
$(document).on("click", ".MyDivClass", function(){...
The variable i will, as you noticed, will contains the value set on the last iteration. Change
console.log("#a" + i + "clicked");
by
console.log(this.id + " clicked");
Within the event handler, this is the target DOM element for the event.
You can do it in this way:
$('[id^="a"]').click(function () {
console.log(this.id+" clicked");
});
You may assign a click event to a class instead of to specific ID's and use conditional statements within the click function to do different things base on ID.
$(documnet).ready(function(){
$('.clickclass').click(function(){
/* conditional code here */
});
});

use of Jquery .after() for moving an element around

I'm reading the jquery manual regarding the .after() function:
$('.container').after($('h2'));
and it says
"If an element selected this way is inserted elsewhere, it will be
moved rather than cloned"
So if I have multiple
<div class='before' onclick='afterfunction();'><div>,
and I would want to place <div class='after'></div> after whichever div is clicked (have it move, not clone) would I do something like this?
var afterdiv = "<div class='after'></div>";
function afterfunction() {
$(this).after(afterdiv);
}
Thanks for all your help!
Like you said:
An element in the DOM can also be selected and inserted after another element:
$('.container').after($('h2'));
If an element selected this way is inserted elsewhere,
it will be moved rather than cloned:
But you missed the bold part.
$('.before').click(function() {
afterfunction(this);
});
// this will not work cause you'll append a string to your DOM
// var afterdiv = "<div class='after'>ola</div>";
// and will repeatedly be appended after each action.
// instead define your element by wrapping it into a $( )
var afterdiv = $("<div class='after'>ola</div>");
// now 'afterdiv' variable is binded to that element only once inside the DOM
function afterfunction(elem) {
$(elem).after(afterdiv);
}
And you don't need to .remove() it (like wrongly suggested in an answer here.)
demo jsFiddle
Make .before div like this:
<div class='before'><div/>
Then try,
$('.before').on('click', function() {
afterfunction(this);
});
function afterfunction(el) {
var afterdiv = "<div class='after'></div>";
$('.after').remove(); // remove previous `.after`
$(el).after(afterdiv); // add newly after the clicked div
}
DEMO

jquery append to already appended div

Is it possible to append something to a div that was already appended? I tried but nothing happens.. (I'm not using linebreaks in the actual js)
$(document).ready(function() {
$('.add_text_input').click(function() {
$('li').append('<div class="input_label">Untitled</div>\
<div class="edit_label"></div>\
<input type="text" name="untitled" /><br />');
});
$('.input_label').click(function() {
var input_label = $(this).html();
$(this).hide();
$('.edit_label').append('<input type="text" name="untitled" value="' + input_label + '"/><br />');
});
});
The js is for creating text inputs and editing their labels. When clicking on the "input_label" div, it should hide using hide() and append a text input with the default "untitled" value in the "edit_label" div. It works if the divs already exist but I need to make it work via append.
Does anyone have any ideas please?
You just need to use a .live() handler here, like this:
$('.input_label').live('click', function() {
var input_label = $(this).html();
$(this).hide().next('.edit_label')
.append('<input type="text" name="untitled" value="' + input_label + '"/><br />');
});
This will work on elements regardless of when they're created, since it works off event bubbling, it'll work on any element's click event that matches the .input_label selector.
Currently with .click() it's finding all the elements that exist at document.ready time and binding to those elements, not to the selector, so it won't work for dynamically added elements.

Categories

Resources