I am currently trying to toggle the visibility of a download button after the user has submitted their email. This submission is done from a regular Elementor form. Although elementor provides a range of actions, it seems like I can only toggle the visibility of the button with my own code. However, I can not hook to the correct action for some reason.
<script>
let button = document.getElementById('pdfdownloadbutton');
let form = document.getElementById('signupform');
document.addEventListener('DOMContentLoaded',()=>{
button.style.visibility = 'hidden';
});
form.addEventListener('submit',()=>{console.log("ev trig");});
</script>
I expected to log in whenever the event was called, however, the console shows an error saying that 'addEventListener' is not a property of null. I assume the document can not locate a form with said id, but, I did name it correctly. Here is the part where I name the id of the form
CodePudding user response:
A few things to note here without having much context on the rest of your code:
- You're listening for a submit event on what appears to be a button, but submit events only fire on form elements. Read more in MDN.
- You're running an
alert
in the submit event handler, an alert won't do anything to show or hide your button, it will only show a browser alert with the string passed to it in the parenthesis. More on that in MDN. - Depending on when your code runs, adding an event listener to
DOMContentLoaded
(MDN) may not do anything, it may be best to start with the button hidden, and then add a class to it to show it when appropriate. The class must be targeted by some CSS, of course.
Here's my shot in the dark at addressing the high level idea you're expressing here:
const form = document.getElementById('signupform');
const pdfButton = document.getElementById('pdfdownloadbutton');
form.addEventListener('submit', function (event) {
// preventDefault added to be able to show the button in this example
event.preventDefault();
pdfButton.classList.add('show');
});
Additionally, you'll need some CSS for the code above to work:
#pdfdownloadbutton {
visibility: hidden;
}
#pdfdownloadbutton.show {
visibility: visible;
}
You can see it in action in this Codepen.
Note that your code doesn't give the full content so I had to fill in the blanks. Particularly, notice how I added event.preventDefault()
(MDN) because the normal behavior of a submit event would load a new page, so you should consider if this is happening on your site in which case you may need a different solution than your current approach.
CodePudding user response:
<div >
<h1>(Write heading)</h1>
<p>(Write description)</p>
<form>
<input type="email" placeholder="Please enter your email !">
<input type="submit" value="subscribe" >
</form>
</div>