[ how to make onclick event on an id beginning by a # in javascript ]
Hey guys im trying to trigger the mailchimp modal with a onclick event.
Two things, I found this post and was able to salvage the following code.
document.getElementById("open-popup").onclick = function() {
showMailingPopUp();
};
function showMailingPopUp() {
document.cookie = "MCEvilPopupClosed=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
require(["mojo/signup-forms/Loader"], function(L) {
L.start({
"baseUrl":"mc.us8.list-manage.com",
"uuid":"a56ce2128001bdcb7974e9ea2",
"lid":"1d4c16bd94"
})
})
};
which looks great and all but i get the following console error.
Uncaught TypeError: Cannot set property 'onclick' of null
so i wrap the code with a window.onload = function () {}
and now have the following
window.onload = function() {
document.getElementById("open-popup").onclick = function() {
showMailingPopUp();
};
function showMailingPopUp() {
document.cookie = "MCEvilPopupClosed=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
require(["mojo/signup-forms/Loader"], function(L) {
L.start({
"baseUrl":"mc.us8.list-manage.com",
"uuid":"a56ce2128001bdcb7974e9ea2",
"lid":"1d4c16bd94"
})
})
};
}
but im still getting the same error. Here's my html markup as well
<section class="hero text-center">
<div class="container">
<h1><b>Start Getting Paid for Your Homework</b></h1>
<h2><b>MAKE REAL USE OF YOUR HOMEWORK</b></h2>
<a class="btn btn-default" href="#" role="button" id="#open-popup-">Join Now</a>
</div>
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" class="separator" viewBox="0 0 100 100" preserveAspectRatio="none">
<path d="M0 100 L100 0 L100 100 Z" fill="#fff"></path>
</svg>
</section>
I precise, the button i need to click have a id beginning by a #
Answer 1
Try to remove the hashtag from your HTML element
<a class="btn btn-default" href="#" role="button" id="#open-popup-">Join Now</a>
to
id="open-popup"
The error clearly states: Cannot set property 'onclick' of null So it doesn't find your HTML element
Answer 2
The # before the string "open-popup-", cause an error because this is a language defined symbol, used to catch any id with jquery from your DOM.
you have to remove it (i don't know if you can, but must!)
A cheaper alternative, is to check if any id is containing the end occurrence of the name:
**
EDIT: since your post have been edited, removing jquery usage.
**
In javascript
document.getElementById("#open-popup-").addEventListener('click',showMailingPopUp());
or with jquery
$("[id~='open-popup-']").on("click", function()
{
showMailingPopUp();
});