When I click on the link it's working perfectly but only ONCE.
I want to be able to be able to keep the addEventListener even after it's been executed.
<div id=myBox>
append
</div>
document.getElementById("append").addEventListener("click", appendMore);
function appendMore() {
myBox.innerHTML += '1';
}
You'll want to use a separate element to insert your content into.
document.getElementById("append").addEventListener("click", appendMore);
function appendMore() {
tgt.innerHTML += "1";
}
<div id=myBox>
append
<span id="tgt"></span>
</div>
// Parent element
var el = document.querySelector('#myBox');
// Find append and add listener
el.querySelector("#append").addEventListener("click",appendMore);
function appendMore( event ) {
// Append new text node
el.appendChild( document.createTextNode('1') );
}
It would be achieved easily by using jQuery.
$('#append').click(function () {
$('#myBox').append('1');
});
find this JSFIDDLE
NB: Please let us know if you want to achieve this using just plain javascript.
Related
I would like to change my icon from expand_more to expand_less in following code
<li class="dropdown-bt" onclick="dropdown('content');">
<a>dropdown-content <i class="material-icons">expand_more</i></a>
</li>
I am going to use same code multiple times so it would be better to using function multiple times. I thought of using ID for every piece of code but it would be to hectic. So I want to write single function do it but I don't know how, so please help.
Just pass an object event as a parameter, say e to your dropdown() and use the textContent property to retrieve the current element content, check it's value and replace the content with another text content like this:
var btn = document.getElementById("dropdownBt");
function dropdown(e) {
var innerText = e.target.children[0];
if(innerText.textContent == "expand_more") {
innerText.textContent = "expand_less";
} else {
innerText.textContent = "expand_more";
}
}
btn.addEventListener('click', dropdown);
<li class="dropdown-bt" id="dropdownBt"><a>dropdown-content <i class="material-icons">expand_more</i></a></li>
In HTML, I have
<div>
<button onclick="action()">button</button>
</div>
Without giving an ID or class to the div element, what can I do in JavaScript to get an access to it and use it?
Pass this into action:
<button onclick="action(this)">button</button>
and then in action
function action(btn) {
var div = btn.parentNode;
// ...
}
or if you want a bit more flexibility, use the (relatively-new) closest method:
function action(btn) {
var div = btn.closest("div");
// ...
}
Side note: Rather than onxyz-attribute-style event handlers, consider using modern event handling (addEventListener, attachEvent on obsolete browsers). If you have to support obsolete browsers, my answer here provides a function you can use to deal with the lack of addEventListener.
Grab the event then get the currentTarget then find the parentNode. Very simple way to do it. This will work no matter which element is clicked. Please see code snippet demonstration.
function getParentNode(event) {
console.log(event.currentTarget.parentNode);
}
<div id="div1"><button onclick="getParentNode(event)">Click</button></div>
<div id="div2"><button onclick="getParentNode(event)">Click</button></div>
using this in the onclick=action() and then the parent is .parentNode
then your method would look like :
<div>
<button onclick="action(this);">button</button>
</div>
function action(el) {
console.log(el.parentNode);
}
but I rather prefer .addEventListenerand for your next question then :
var $el = document.getElementById("a");
$el.addEventListener("click", function(e) {
// Create a <button> element
var btn = document.createElement("BUTTON");
// Create a text node
var t = document.createTextNode("CLICK ME");
// Append the text to <button>
btn.appendChild(t);
// Append <button> to the parentNode
this.parentNode.appendChild(btn);
});
<div>
<button id="a">Button</button>
</div>
Also in case you wonder for a shorter version and probably introducing to the jQuery :
;$(function(){
$("#a").on("click", function(e) {
$(this).parent().append('<button>Click Me</button>');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<button id="a">Button</button>
</div>
Another but not straight way to get the parent instead of .parentNode is .closest() method:
element.closest("div"); // also supported in jQuery
Returns the first ancestor of element, that is a <div> element:
If it is possible, pass this (button) to action. Then you can access parent by element.parentNode. Example: https://jsbin.com/fidufa/edit
I'm generating a div dynamically and I've to check whether a dynamically generated div exists or not ? How can I do that?
Currently I'm using the following which does not detects the div generated dynamically. It only detects if there is already an element with the id contained in the HTML template.
$(function() {
var $mydiv = $("#liveGraph_id");
if ($mydiv.length){
alert("HHH");
}
});
How can I detect the dynamically generated div?
If mutation observes aren't an option due to their browser compatibility, you'll have to involve the code that's actually inserting the <div> into the document.
One options is to use a custom event as a pub/sub.
$(document).on('document_change', function () {
if (document.getElementById('liveGraph_id')) {
// do what you need here
}
});
// without a snippet to go on, assuming `.load()` for an example
$('#container').load('/path/to/content', function () {
$(this).trigger('document_change');
});
If it is added dinamically, you have to test again. Let's say, a click event
$("#element").click(function()
{
if($("#liveGraph_id").length)
alert("HHH");
});
How you inserting your dynamic generated div?
It works if you do it in following way:
var div = document.createElement('div');
div.id = 'liveGraph_id';
div.innerHTML = "i'm dynamic";
document.getElementsByTagName('body')[0].appendChild(div);
if ($(div).length > 0) {
alert('exists'); //will give alert
}
if ($('#liveGraph_id').length > 0) {
alert('exists'); //will give alert
}
if ($('#liveGraph_id_extra').length > 0) {
alert('exists'); //wont give alert because it doesn't exist.
}
jsfiddle.
Just for interest, you can also use a live collection for this (they are provided as part of the DOM). You can setup a collection of all divs in the page (this can be done in the head even before the body is loaded):
var allDivs = document.getElementsByTagName('div');
Any div with an id is available as a named property of the collection, so you can do:
if (allDivs.someId) {
// div with someId exists
}
If the ID isn't a valid identifier, or it's held in a variable, use square bracket notation. Some play code:
<button onclick="
alert(!!allDivs.newDiv);
">Check for div</button>
<button onclick="
var div = document.createElement('div');
div.id = 'newDiv';
document.body.appendChild(div);
">Add div</button>
Click the Check for div button and you'll get false. Add the div by clicking the Add div button and check again—you'll get true.
is very simple as that
if(document.getElementById("idname")){
//div exists
}
or
if(!document.getElementById("idname")){
// don't exists
}
So I have EDIT and REMOVE buttons that are dynamically added for each data node (a "poll") in a Firebase database. I have a function which assigns onclick listeners to these with jQuery, but oddly, the event only fires when there just happens to be a single node, and hence a single pair of EDIT/REMOVE buttons. When there are multiple nodes and multiple pairs of buttons, none will fire. Here's the javascript where the events are added to the buttons...
function displayCurrentPollsForEditing(pollsRef)
{
var tbl = createTable();
var th = ('<th>Polls</th>');
$(th).attr('colspan', '3');
$(th).appendTo($(tbl).children('thead'));
pollsRef.once('value', function(pollsSnapshot) {
pollsSnapshot.forEach(function(pollsChild) {
var type = pollsChild.name();
// If this is true if means we have a poll node
if ($.trim(type) !== "NumPolls")
{
// Create variables
var pollRef = pollsRef.child(type);
var pollName = pollsChild.val().Name;
var btnEditPoll = $('<button>EDIT</button>');
var btnRemovePoll = $('<button>REMOVE</button>');
var tr = $('<tr></tr>');
var voterColumn = $('<td></td>');
var editColumn = $('<td></td>');
var rmvColumn = $('<td></td>');
// Append text and set attributes and listeners
$(voterColumn).text(pollName);
$(voterColumn).attr('width', '300px');
$(btnEditPoll).attr({
'class': 'formee-table-button',
'font-size': '1.0em'
});
$(btnRemovePoll).attr({
'class': 'formee-table-remove-button',
'font-size': '1.0em'
});
$(btnEditPoll).appendTo($(editColumn));
$(btnRemovePoll).appendTo($(rmvColumn));
// Append to row and row to table body
$(tr).append(voterColumn).append(editColumn).append(rmvColumn);
$(tr).appendTo($(tbl).children('tbody'));
// Append table to div to be displayed
$('div#divEditPoll fieldset#selectPoll div#appendPolls').empty();
$(tbl).appendTo('div#divEditPoll fieldset#selectPoll div#appendPolls');
$(btnEditPoll).click(function() {
displayPollEditOptions(pollRef);
return false;
});
$(btnRemovePoll).click(function() {
deletePoll($(this), pollsRef);
return false;
});
}
});
});
}
The markup would be something like the following...
<div id="divEditPoll">
<form class="formee" action="">
<fieldset id="selectPoll">
<legend>SELECT A POLL</legend>
<div class="formee-msg-success">
</div>
<div class="grid-12-12" id="appendPolls">
</div>
</fieldset>
</div>
EDIT - So I've switched some lines around and now I don't set the click() events until the buttons are appended to the document, so the button elements are definitely in the DOM when the click events are attached. So could this issue result from not setting id's for these buttons? That seems strange to me, since I'm using variable references rather than ids to attach the events.
There are two things I would check for.
First, make sure you don't have two elements with the same id. If you do, jquery may only bind to the first, or not bind at all.
Second, make sure the element is added to the dom before jquery attempts to bind the click event. If the code is running asynchronously, which can easily happen if you're using ajax, then you may be trying to bind the event before creating the element. Jquery would fail to find the element then give up silently.
you should use .on() for dynamically added button
is there a way to reset/update an after() element? Not add another after() text. Thank you
Maybe this will helpful.
(Controller function for Emptiness of Form to be sent Server Input parameter ID of Form Parent DIV, output is 1-true, 0 false)
function emptynessCntrl(elementosForControl){
var controlResult=1;
$(elementosForControl).find('input').each(function() {
if($(this).val().trim()===""){
controlResult=0;
console.log($(this).attr('id')+' Element is empty');
$(this).nextAll().remove();
$(this).after('<div class="err-label">'+$(this).attr('placeholder')+' is empty</div>');
return controlResult;
}
else{
$(this).nextAll().remove();
}
});
return controlResult;
}
Your question is not clear. I'll asume you want to modify an element added with .after()
Instead of doing this:
$("#elem1").after('<div id="after />");
You could do this (use insertAfter)
$('<div id="after" />').insertAfter("#elem1").attr("width", 200).html("hi") ...;
Hope this helps.
Cheers.
When you add the element, give it a name
var newElement = $('<span>Some new stuff</span>');
$('.whatever').after(newElement);
Then, when you want to change it, simply remove the previous one first
newElement.remove();
newElement = $('<div>And now for something completely different</div>');
$('.whatever').after(newElement);
You can write a function that uses .data() to remember the new element as such: (I would change the names a bit though)
$.fn.addUniqueSomething = function (content) {
var existing = this.data('something-that-was-already-added');
if (existing) {
existing.remove();
}
var something = $(content);
this.after(something);
this.data('something-that-was-already-added', something);
};
Then you can use
$('.whatever').addUniqueSomething('<span>Some new stuff</span>');
// and later...
$('.whatever').addUniqueSomething('<div>And now for something completely different</div>');
And the second one will replace the first