Javascript on event listener click not working

I have this code to show a modal.

  var quotebtn = document.querySelector("#quoteBtn");
  quotebtn.addEventListener("click", function () {
    document.querySelector("#getaquote").css({ "opacity": "0" });

With the html syntax:

    <div class="flex justify-center w-full">
        <a href="javascript:;" id="quoteBtn" class="primary-btn mt-16">Get a quote</a>

For some reason it isn’t working.

I think it’s not working because the browser processed the javascript file before the HTML and at that time, there wasn’t any element with that id. Open up your console(developer tools) and have a look what it says.

It appears the code did not procced due to another error.
You’re accessing handleSubmit before you declared it.

I removed the code causing the error and now there are no console errors, however the onclick event still does not work.

Just added an alert to the onclick and it fired like normal, seems there must be an issue with document.querySelector("#getaquote").css({ "opacity": "0" });

I’m afraid you cannot change the css property of HTML element as it does not exist. You can however change its style property.

 document.querySelector("#getaquote").style.opacity = 0;

Thank you very much, is there any way to add more styles in one statement?


 document.querySelector("#getaquote").style.opacity = 0 + display = none;

But I know where you are coming from. This element.css() is from jQuery library.
In that case you would need to select it as:

$("#getaquote").css({ "opacity": "0", ... });

$(selector) and document.querySelector(selector) are two different things.

If you’re using jQuery in your project, just stick with it and don’t mix it with browser native querySelector method.

This syntax breaks my :heart: .

1 Like

Thanks for your help.

jQuery was made to make our lifes easier. I’ve never worked with it, however, I believe that in the background it changes elements style properties one by one as you’d have to.

document.querySelector("#getaquote").style.opacity = value;
document.querySelector("#getaquote").style.display = value;

or you could write your own function to achieve the same result…
I’ll try here just for fun.

function setStyles(selector, styles = {}) {
    const element = document.querySelector(selector);
    for (const [key, value] of Object.entries(styles)) {[key] = value;
setStyles("body", {"backgroundColor": "purple"})

You can copy paste this and run it in your browser’s console for example.

1 Like

Is everything working as you want now?

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.