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>');
Related
I'm trying to apply a border to a dynamically generated element using $.on('click') and $.addClass(), but the class doesn't seem to be applied on the first click event. Otherwise, it works fine. What am I doing wrong?
$(document.body).on('click', '.card', function() {
var currentSelection = $(this)
var currentSelectionIndex = $(currentSelection).index()
$(currentSelection).addClass("selected")
if (currentSelectionIndex !== previousSelectionIndex) {
p = $("#searchResponse").children().get(previousSelectionIndex)
$(p).removeClass("selected")
}
previousSelectionIndex = currentSelectionIndex;
});
Solution: Assigning previousSelectionIndex a value a the beginning of my script and it fixed the issue.
I'm not entirely clear on your question given the information provided.
However, if I understand the problem correctly you have a container element with the id="searchResponse" that has many children each with the class="card" and you're essentially trying to add class="selected" to a particular card when it is clicked ensuring that only one card at a time can be 'selected'. If this is the case..
Select only one card at a time:
$('#searchResponse').on('click', '.card', function(){
$('.card.selected').removeClass('selected');
$(this).toggleClass('selected');
});
If you need to select and unselect multiple then try this:
$('#searchResponse').on('click', '.card', function(){
$(this).toggleClass('selected';)
});
Working Codepen
I am creating several buttons once I read some data from a JSON file. The buttons are being create this way:
element.after('<button class="button ' + subcategoriesData.tag + '" category="' + category.tag + '" subcategory="' + subcategoriesData.tag + '">' + subcategoriesData.title + '</button>');
I want to create a click as soon as the page loads so one of these buttons is automatically selected.
I have tried to select one of the elements and trigger a .click() but still, this didn't work. I have also tried to find the element from its parent element and trigger a .click() but still, it didn't work.
Do you have any ideas what else I can try?
Since you are using jquery, you may want to consider using jQuery to create the element this way (then you don't have to worry about managing the syntax:
$("<button/>").attr({
class: "button",
category: category.tag,
subcategory: subcategoriesData.tag
}).appendTo("#elementID");
The appendTo method will append using any selector. You can also attach to the click event using .on("click", function(e) { }) within this statement as well.
Whatever solution you use to create the button, $(".button:first").trigger("click") will trigger the click event; if it's not firing, run your selector with a .length property check and see if it's returning 0; if it is, the selector isn't finding the button.
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 */
});
});
I'm trying to build a sticky note with Javascript and jQuery. The problem I am having is, that the functions draggable() and deleteNote() can not be called on the newly appended elements. How can I fix this?
EDIT: The ID actually should get an added number, which I'm not sure how to implement, because I don't know how to create a counter. E.g. newbox1
My code on jsfiddle: http://jsfiddle.net/wowpatrick/qexRS/4/
You need to attach the eventhandlers live, since there are no elements existent at the moment you initially called them.
Use jQuerys live() (Attention:deprecated Docu) or with new jQuery-version on() (Docu), to be able to attach the events on each newly created note.
Also don't use IDs, since this produces invalid markup because IDs always have to be unique. Use classes instead.
You could add the .click handlers to the new element after you create it.
You shouldn’t create multiple elements with the same ID, use class instead.
Also, you can attach the .draggable() to the created element right away instead of targeting $('#newbox').
Here is a fork that works better: http://jsfiddle.net/YvtLb/
The key is here:
var postit = $('<div class="ui-widget-content newbox" style="top:' + e.pageY + 'px; left: ' + e.pageX + 'px;"><span id="close">Delete comment</span><p>Your comment:</p><textarea></textarea></div>').draggable();
$('#canvas').append(postit);
This is because on page load #newbox does not exist. A better method would be to store your new element in a variable, append it, then apply draggable, try this:
// Create the new comment at the corsor postition
var $newbox = $('<div class="ui-widget-content" id="newbox" style="top:' + e.pageY + 'px; left: ' + e.pageX + 'px;"><span id="close">Delete comment</span><p>Your comment:</p><textarea></textarea></div>');
$('#canvas').append($newbox);
$newbox.draggable();
Example fiddle
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.