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.
Related
Let's say I have this piece of HTML code:
Plugin 1
Plugin 1 options 1
Plugin 1 options 2
Header 2
Plugin 1 options 1
<div id="content"></div>
Whenever I click "Plugin 1" a table is generated inside Content div with headers containing "Plugin 1 options 1", "Plugin 1 options 2" etc. strings in them and the plugin options submenu have their "display" attribute turned to "block".
I want to add an event listener to the "Plugin 1 options 1/2" elements so the page would scroll to the table header element with the same value.
How can I do that, as the elements of the table are created after the page is loaded?
Edit 1: It is not a problem of adding an event handler to not existing elements, as they are created at the very beginning. Problem here is that I want to add an event handler to existing element that will manipulate an element that will be created in the future. Here is an example from my code:
var table_element = $('th:contains("' + plugin_name + '")');
group_button.click(function () {
table_element.get(0).scrollIntoView();
});
group_button exists from the begging, where table_element is generated dynamically. Moreover, I checked whether $('th:contains("' + plugin_name + '")') is a correct selector, by passing it console when table was generated.
Since the event listener cannot manipulate the element until it is rendered, it is safe to assume, the action need only be performed once it has a value.
So, you could just use the selector inside the listener to get access to the DOM element instead of trying to store a reference of an element that could render in future.
group_button.click(function () {
var table_element = $('th:contains("' + plugin_name + '")');
if(table_element.get(0))
table_element.get(0).scrollIntoView();
});
This way, if the element exists, it would be scrolled into view.
You need to make table_element local to event handler.
group_button.click(function () {
var table_element = $('th:contains("' + plugin_name + '")');
table_element.get(0).scrollIntoView();
});
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>');
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
I have some search results that I'm outputting that are of this form:
<div id="result" title="nCgQDjiotG0"><img src="http://i.ytimg.com/vi/nCgQDjiotG0/default.jpg"></div>
There is one of these for each result. I'm trying to detect which one is clicked and then do some stuff. Each result has a unique title, but the same id. How do I use .click() to know which one was clicked so I can get it's ID and use it?
Here's how I'm getting the HTML from above:
$.each(response.data.items, function(i,data)
{
var video_id=data.id;
var video_title=data.title;
var video_thumb=data.thumbnail.sqDefault;
var search_results="<div id='result' title='"+video_id+"'><img src='"+video_thumb+"'></div>";
$("#searchresults").append($(search_results));
I tried
$('div').click(function(){
alert(this.id);
});
and the alert says "searchresults" (no quotes).
Additionally, this is the perfect opportunity to make use of event delegation. With this technique, you do not have to worry about re-binding click handlers after programmatic insertion of new DOM elements. You just have one handler (delegated) to a container element.
$("#searchresults").delegate("div", "click", function() {
console.log(this.id);
});
See .delegate
You can't have the same ID on multiple tags. You will have to fix that. You can use the same class, but there can only be one object in the page with a given ID value.
this.id will fetch the id value of the item clicked on and this should work fine once you get rid of conflicting IDs:
$('div').click(function(){
alert(this.id);
});
This code should be something this:
var search_results="<div id='result'" + video_id + " title='"+video_id+"'><img src='"+video_thumb+"'></div>";
$("#searchresults").append(search_results);
to coin a unique id value for each incarnation and append will just take the string - you don't need to turn it into a jQuery object.
you could get the title using $(this).attr("title").val()