This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
How to find if element with specific id exists or not
(8 answers)
Closed 5 years ago.
My site serves dynamic contents so the header and footer remains the same. In the footer is my JS script that has a few document.getElementById('ids').addEventListener('click',function(e).
How can I prevent the JS error TypeError: document.getElementById(...) is null when the content with the element ID was not yet served? See sample JS code below:
<script>
// DN_1, 1st page Switch On/Off
document.getElementById('dn_1_yes-no').addEventListener('click',function(e){
var attrChk = document.getElementById('dn_1_yes-no');
if( this.checked){
document.getElementById('external_dn_1').style.display='block';
}else{
document.getElementById('external_dn_1').style.display='none';
}
});
// DN_2, 2nd page Switch On/Off
document.getElementById('dn_2_yes-no').addEventListener('click',function(e){
var attrChk = document.getElementById('dn_2_yes-no');
if( this.checked){
document.getElementById('external_dn_2').style.display='block';
}else{
document.getElementById('external_dn_2').style.display='none';
}
});
// more.....
</script>
This works!
<script>
var dn1Ele = document.getElementById('dn_1_yes-no');
var dn2Ele = document.getElementById('dn_2_yes-no');
if(dn1Ele != null) {
// DN_1 Switch On/Off
document.getElementById('dn_1_yes-no').addEventListener('click',function(e){
var attrChk = document.getElementById('dn_1_yes-no');
if( this.checked){
document.getElementById('external_dn_1').style.display='block';
}else{
document.getElementById('external_dn_1').style.display='none';
}
});
}
if(dn2Ele != null) {
// DN_2 Switch On/Off
document.getElementById('dn_2_yes-no').addEventListener('click',function(e){
var attrChk = document.getElementById('dn_2_yes-no');
if( this.checked){
document.getElementById('external_dn_2').style.display='block';
}else{
document.getElementById('external_dn_2').style.display='none';
}
});
}
// more.....
</script>
Related
This question already has answers here:
Attach event to dynamic elements in javascript
(15 answers)
Closed 3 years ago.
Hi I am trying to create a list that is partially shown and if you click read more you will be able to see all the list. I have found this plugin: https://github.com/solarmosaic/jquery-show-first
However when I try to use it on newly inserted HTML from javascript it does not work. It works if the HTML is in the HTML file in the beginning.
Here is part of my code:
var associatedEntities = associated[a].split("|");
var personDone = false;
var placeDone = false;
var keywordDone = false;
var itemDone = false;
for (var d = 0; d<associatedEntities.length; d++){
if(associatedEntities[d].includes("#")){
var contents = associatedEntities[d].split('#');
if(associatedEntities[d].includes('person/')){
if(personDone == false){
associatedWithHTML+="<ul class = \"show-first\" data-show-first-count=\"3\">";
personDone = true;
}
associatedWithHTML+="<li><a target=\"_blank\" href=\"PersonResult.html?id="+contents[0].trim()+"\" >"+contents[1]+"</a><br></li>";
}else if (associatedEntities[d].includes('place/')){
if(placeDone == false){
associatedWithHTML+="<ul class = \"show-first\" data-show-first-count=\"3\">";
placeDone = true;
}
associatedWithHTML+="<li><a target=\"_blank\" href=\"PlaceResult.html?id="+contents[0].trim()+"-"+contents[1]+"\" >"+contents[1]+"</a><br></li>";
}else if (associatedEntities[d].includes('item/')){
if(itemDone == false){
associatedWithHTML+="<ul class = \"show-first\" data-show-first-count=\"3\">";
itemDone = true;
}
associatedWithHTML+="<li><a target=\"_blank\" href=\"ItemResult.html?id="+contents[0].trim()+"\" >"+contents[1]+"</a><br></li>";
}
}else{
if(keywordDone == false){
associatedWithHTML+="<ul class = \"show-first\" data-show-first-count=\"3\">";
keywordDone = true;
}
associatedWithHTML+="<li><span>"+associatedEntities[d]+"</span><br></li>";
}
}
}
associatedWithHTML+="</ul><hr></div>";
document.getElementById("DeedDate").innerHTML+=newHTML+associatedWithHTML+"</div>";
HTML inserted after page load will NOT have any javascript events/listeners applied to it that would normally be applied to elements with matching ids/selectors on page load (unless you use mutator events).
you must set up event listeners in a certain way to "dynamically" add events whenever the DOM node is inserted.
//Jquery: Instead of this for attaching an event
$(".my-element").click(function() {
//Some code here...
});
//Jquery: You will need to do this to catch all elements
$(document).on("DOMNodeInserted", ".my-element", function() {
$(this).click(function() {
//Some code here...
});
});
//Vanilla javascript
document.addEventListener("DOMNodeInserted", function (e)
{
if(e.target.classList.contains("my-element")) {
e.target.addEventListener("click", function() {
//Some code here...
});
}
}, false);
Now, you are asking this question from the context of a plugin, but this is what is happening. The plugin is not applying its events to things on node insertion, but at page load. You can modify the supplied code to do this, or add something on your side that registers required events on node insertion into the DOM.
Note: Chose only ONE of the two example solutions above that use DOMNodeInserted. This replaces the normal "click" event registration for that element. Do NOT have a click event registered in addition to adding DOMNodeInsert events registered for the same selector.
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 5 years ago.
The change function is not firing to the console after I change the value in the dropdown. When I apply the code in the console and run it, changed!! logs without any problem. What could be the cause of this?
jQuery( document ).ready(function() {
/* Watch for changes in UITVERKOCHT for 50m and 100m pages and change the text */
if(window.location.href.indexOf("prikkabel-50-meter") > -1 || window.location.href.indexOf("prikkabel-100-meter") > -1){
console.log('window location true');
jQuery('#aantal-fittingen').change(function(){
console.log('changed!!');
if(jQuery('.woocommerce-variation-availability > p').text() === "Uitverkocht"){
jQuery('.woocommerce-variation-availability > p').text('Beschikbaar');
}
});
}
});
This is the page when I would like this code to work: https://pkled.wpstagecoach.com/product/prikkabel-50-meter/
This solved my problem:
if(window.location.href.indexOf("prikkabel-50-meter") > -1 || window.location.href.indexOf("prikkabel-100-meter") > -1){
jQuery(document).on('change', '#aantal-fittingen', function() {
if(jQuery('.woocommerce-variation-availability > p').text() === "Uitverkocht"){
jQuery('.woocommerce-variation-availability > p').text('Preferred text');
}
});
}
Thanks to #epascarello
This question already has answers here:
In Javascript, why is the "this" operator inconsistent?
(8 answers)
Closed 7 years ago.
so I have a few buttons and because I don't want to code the same thing for each button I was trying to make a dynamic event handler that could manage all the buttons based on the .selected-pack class but all the $(this) attributes are coming back undefined although there is a value.
This is the js:
//Function In Test!
$('.selected-pack').click(function(event) {
if($("#mainconsole").val() == "") {
alert("Select Your Console!")
return;
}
if($("#paymentmethod").val() == "") {
alert("Select Your Preferred Payment Method!")
return;
}
$("#selectConsolediv").fadeOut("medium", function() {
$("#choosePlatformLI").removeClass("active");
var packipn = $(this).attr('data-ipn');
var packipnpp = $(this).attr('data-ipnpp');
var packname = $(this).attr('data-name');
var packprice = "";
console.log(packname);
if ($("#mainconsole").val() == "PS"){
packprice = $(this).attr('data-psprice');
}
if ($("#mainconsole").val() == "XBOX") {
packprice = $(this).attr('data-xbprice');
}
// Skrill
$("#mainamount").val(packprice);
$("#mainipn").val(packipn);
$("#maindesc").val(packname);
$("#maindiscount").val($("#discount1").val());
// PayPal
$("#mainamountpp").val(packprice);
$("#mainipnpp").val(packipnpp);
$("#ppitemname").val(packname);
$("#maindiscountpp").val($("#discount1").val());
$("#checkoutPackName").text(packname);
$("#checkoutCode").text($("#discount1").val());
$("#checkoutPrice").text("£" + packprice);
$("#checkoutdiv").fadeIn("medium", function() {
$("#checkoutLI").addClass("active");
});
});
});
Do any of you spot an error? Please give me a comment as soon as possible, thanks in advance :)
It's because the scope of $(this) changes inside the fadeOut() callback. Try adding:
var self = $(this);
at the top immediately after $('.selected-pack').click(function(event) { and use self instead throughout.
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 7 years ago.
i am trying to add a new span of tag inside tags div.
my problem is that the code under span[id="newtag"] doesnt
work. how can i make this code work?
$(document).ready(function () {
$('#tags').on("click", function () {
$(this).append('<span id="newtag" contenteditable="true"></span>');
$(this).children(":last").focus();
});
$('span[id="newtag"]').keypress(function (k) {
if (k.which == 13 || k.which == 32) {
$(this).append('gfskjsokdfla');
}
});
});
Use event delegation for created dymanically dom elements.
$('#tags').on('keypress', 'span[id="newtag"]', function(k){
if (k.which == 13 || k.which == 32) {
$(this).append('gfskjsokdfla');
}
});
This question already has answers here:
How to trigger jQuery change event in code
(5 answers)
Closed 8 years ago.
I know that it is possible to do in two functions, but I am not sure how to make it in one.
$("#purchase_sub_type").change(function() {
if($(this).val() == 15) {
console.log('is 15');
}
else {
console.log('not 15');
}
});
This is example code. Problem is that this code works only on change, not when value is loaded form DB on page reload. Is there simple way to add current val to this function? I know that it is possible adding another function, but in that way code gets ugly and repeats.
Trigger the change event so the code fires
$("#purchase_sub_type").change(function() {
if($(this).val() == 15) {
console.log('is 15');
}
else {
console.log('not 15');
}
}).change(); //or .trigger("change");
Generally it is good idea to give function a name.
var field = $("#purchase_sub_type");
function log () {
if(field.val() == 15) {
console.log('is 15');
}
else {
console.log('not 15');
}
};
field.change(log);
log();