Script explanation : I have a text area which user is typing notes and those notes are added to the DOM (as div elements) . I created an icon inside that divs that when you click on it i want the parent of the icon that is clicked to be removed from the DOM . I achieve this with JQuery , but i cant do it in pure JS. The code i use to achieve this in:
$('.fa-window-close').on('click', function(event){
event.preventDefault();
console.log($(this).parents('div')[0]);
$(this).parents('div')[0].remove();
});
Iam posting a link from gist, its a part code of my project so you can understand what iam trying to achieve.
https://gist.github.com/Clickys/43856fe26ee4c061cf910a9211f0c142
Basically what i want to achieve is , lets assume that we have a button that is creating divs elements inside DOM. Each of this div has an icon(fontawesome) that if we click on it , the selected target should be removed from the DOM(the target div) but not the other divs . I tried to use event.target and a lot of things but sadly i couldn't solve this with pure JS.
I tried this
closeTolPos.addEventListener('click', function(e){
var parentEl = e.currentTarget.parentNode.parentNode;
parentEl.removeChild(this.parentElement);
console.log(this.parentElement);
});
But it seems that when there are more than 1 element , it doesnt work . It only works if there is one element.
We make some changes and now the code works:
(function() {
document.addEventListener('click',function(e) {
if (e.target.closest('.notesDecoration')) {
e.target.closest('.notesDecoration').parentNode.removeChild(e.target.parentNode);
}
});
})();
Now click event is binded to a document, so the element exists, when the page is loaded. Then I check if the clicked element was the element, which was recently created and added to DOM.
Related
To place an external widget without having to let non-technical people paste embed code on every desired spot on a webpage, I'm working on a visual div and p tag selector where people can just pinpoint the desired element(s).
When people hover over an element, it will show a red border to show them what's selected.
For us to place the widget, normally we would target by class or id. However, the class / id should be unique for it to work and unique classes for a random div / p tag is pretty rare.
Via a piece of jquery code:
$(document).on('mouseenter mouseleave', '.sj-highlight',
function (e) {
}
I can get the DOM details about the selected element.
Is there a way I can target the highlighted element by using some data from the DOM details and if yes how?
Tried the code above but just don't know much about DOM selecting possibilities.
To make the whole highlight per element possible, I wrote this:
$( document ).ready(function() {
$('div, p').each(function(i){
$(this).addClass('sj-highlight sjhighlight'+i+'');
$(this).attr('data-sj', 'sjhighlight'+i+'');
});
$(document).on('mouseenter mouseleave', '.sj-highlight', function (e) {
var sjhighlighter = $(this).attr("data-sj");
// hide other highlights
$('.sj-highlight').css("border","2px solid transparent");
if(e.type == 'mouseenter')
{
$('.'+sjhighlighter+'').css("border","2px solid #ff0000");
}
});
The end result would be to somehow target the selected elements with the DOM instead of a class or id.
From the pieces that i put together i think if you can get to the element using
$(document).on('mouseenter mouseleave', '.sj-highlight',
function (e) {});
that means you already have it, because $(document).on() form works for dynamically added elements (that means even if you add element dynamically it still works properly), you can use :
var elementClass = $(this).attr('class');
and you have complete control over the element from there.
And you have also all possibility over its children or it parent which returned as dom elements objects.
I think that your question need a little bit of clarification too.
Here is an option that I used when trying to target elements without the ID or Class. You first need to figure out what each of these highlighted elements have in common. Either it be a specific color, element hierarchy, etc. Then you could use the filter() jquery to find all elements with that spec. This is what I used.
/*select an element that contains this piece of code your trying to target*/
$('#Parent_container').filter(function() {
/*here you will specify what you're trying to identify or target*/
return $(this).find('div[class="sj-highlight"]').length >0;
/*optional but you can create a condition to add code or do whatever you want*/
}).find('div[class="sj-highlight"]').after('<p>some stuff</p>');
Hope that helps. It might give you some idea of what options you have.
I am still a bit new to JS & JQuery, so please excuse what may be a simple and stupid question.
Background:
I have a div on my page that holds several divs (#idle-variable). On click of the top level div, it basically shows the other divs (#addvariable). Nothing more than display: none; and .show(). Easy. On another action within that div (change of drop down), I essentially want to inject/insert that top level div (#idle-variable) underneath the first instance.
Issue:
Essentially, the .click function is not working on my newly inserted div. This may be because the two div's share the same ID, BUT I have a sneaky suspicion that it's not recognized in the DOM. A friend of mine said something about I have to "re-run" my jquery in order for it to be readable in the DOM.
Question:
How can i make this work properly? I want to be able to add a dynamic number of these idle-variables to the page and I need to make sure my .click function works for all added DIVS.
$(function(){
$('#idle-variable').click(function(event) {
$("#addvariable").show(400);
});
});
//create variable in db & show value entry
$("#variabletype").change(function() {
$("#varholder").css("display", "inline-block");
$.ajax({
type: "POST",
url: "/myphpfile.php",
data: {"variabletype": $("#variabletype").val()},
success: function(){
$( "#idle-variable" ).after("<div id="#idle-variable>content</div>");
}
});
});
Well to make the code work it would need to use on and ids are only supposed to be on one element. If it can be on the page multiple times you need to use classes.
$(document).on("click,'#idle-variable', function(event) {
$("#addvariable").show(400);
});
you should be using classes
$(document).on("click,'.idle-variable', function(event) {
//$("#addvariable").show(400); //not sure how this relates to the clicked element.
$(this).find(".addvariable").show(400); //if it is a child
});
You also have a typo in your code with quotes.
The ID based selector will be applied to the first element only.
See the example here http://jsfiddle.net/9GN2P/2/
If you are looking to bind same event handler to multiple elements, definitely go with the class based approach, instead of ID based approach.
And, you are expecting event handler to work with dynamically created elements as well. If you are using older versions of jquery, use the live method like
$('yourselector').live('click',function(){
});
Since live is deprecated and if you are in a new version, use the 'on' method
$('containerselector').on('click','yourselector',function(){
});
Editing to answer your comment:
To create dynamic element and append to DOM, you can follow the bellow pattern. Here, I will create a DIV with id "newID", class "newClass", content "NEW DIV!!" and a click event handler for it. And it will be pushed into another div with id 'containerID'
$('<div />',{
id:'newID',
'class':'newClass',
text:'NEW DIV!!',
click:function(){alert('hi');}
})
.appendTo('div#containerID');
This is just a demo.
I want to add draggable functionality on a div at runtime. The div's id is generated with the following code:
var Exp=0;
view.renderFunction = function(id1){
var id= id1 + Exp++;
$("#"+id).draggable();
};
This is my function where the id is dynamically generated when I drop div.
But when I apply the draggable method it can't move. How can I move div?
It will work, have tested this.
Make sure of the following points:
Make sure you know what is Exp++ (you haven't mentioned about it in the question)
The element on which you call draggable() is a valid DOM element.
Try calling it on document ready or DOM ready
Here is a working fiddle: http://jsfiddle.net/gopi1410/ByWCS/
Are you facing trouble with dragging itself or is the problem only with dropping it anywhere? This should be pretty straight forward. Here is a sample that shows dragging a child div from one parent div to another:
How to enable dragging a div from one parent div to another
var id= id1 + Exp++;
$("#"+id).draggable();
What is Exp++, and are you sure that you are calling .draggable() on an existing element? Also, is that renderFunction ever called with an id?
I used kinetic.js and now it working fine
In javascript, possibly using jQuery, how can I detect if the html content of a given element has changed?
I'd like to be able to do somthing like:
$('#myDiv').change(function(){
// do some stuff
});
I am basically trying to detect if given elements are being added to the div or if the inner html of given elements (such as labels) has changed and then hide or show the div depending on the content.
Any alternative idea about how to achieve smt like this is also appreciated.
I am hoping I won't have to revert to some obscure plugin to do this!
NOTE: this needs to work at least in IE8!
You can use the DOM Level 3 event DOMNodeInserted. Example:
$('#myDiv').bind('DOMNodeInserted', function(e) {
console.log('element: ', e.target, ' was inserted');
});
Demo: http://www.jsfiddle.net/vsgdZ/1/
The event will fire whenever a new node was appended to the element on which you bind the handler.
I am newbie to jQuery and javascript. In my application I have a list of users. When a particular user is clicked from the list, a div element is replaced with details about the user dynamically. When another user is clicked, again I replace the same div element with this user details. So at a time only one user details can be seen.
I use jquery, so my code to the above description looks like.
$('table#moderate_users tr').click(function() {
$.get('/moderate/user/'+uid, function(data){ $('div.user_info').html(data);
});
});
This works perfect and the content is inserted dynamically.
I have a dropdown(html select tag) in the dynamically added content. So I get the dropdown only when i click on a user from the list and it changes repectively when I click on another user. I wanted to find the value of the select tag using jquery whenever it is changed. So I wrote
$('select#assign_role').change(function(){
alert(this.val());
});
Since this dropdown is added after document.ready, adding this script inside document.ready function never worked. I also tried to insert the above script along the with the user details which is dynamically added.For my surprise this script is not inserted into the document at all, while the rest of the HTML content are inserted perfect. I am not aware if i can add insert javascript after the document has loaded. I am not aware how i could use jQuery to find out the value of the select tag which is added dynamically.
Thanks.
you want jQuery's "live" functionality:
$('select#assign_role').live('change',function(){
alert($(this).val());
});
also notice I changed alert(this.val()); to alert($(this).val()); considering that this inside a jQuery event handler references the actual dom element, not a jQuery object.
From the looks of your code, it seems that you are inserting a chunk of HTML into that div. So even if you wire your event to the dropdown after the page load, it will not work, since all of your event binding will be ignored when you insert new HTML code into div.
Try moving your code inside the function that inserts HTML. Something like this:
$('table#moderate_users tr').click(function() {
$.get('/moderate/user/'+uid, function(data){
$('div.user_info').html(data);
$('select#assign_role').change(function(){
alert(this.val());
});
});
});
On IE the live function doesn't work for onchange on <select> elements.
http://www.neeraj.name/blog/articles/882-how-live-method-works-in-jquery-why-it-does-not-work-in-some-cases-when-to-use-livequery
You will need to either add the select then do a setTimeout and then bind with the jquery.bind type of functionality, or, what I have done, is when you create the element then just set the onchange event handler there directly.
If you don't need to support IE then the live function works great.