Adding event listener to specific class not working

Started by Julius_2000, January 07, 2025, 05:50:26 PM

Previous topic - Next topic

Julius_2000

Hi all,

With the help of @Kindred I was able to create a new button for the sceditor. It's supposed to swap classes. For that, I use a codepen example that I customized to my needs in there which worked fine. But for some reason, when I try to transfer that to the forum, the event listener won't come up and the rest of the script wouldn't take effect.

The class I use is .inlineSP which shows up in the inspector just fine. In the js file I use the following simple query:
const spoiler = document.querySelector(".inlineSP");
which is then followed by some functions and if-conditions.

Outside those, I use this code for the listener:
spoiler.addEventListener("click", reveal);
To load the javascript, I put it in the index.template.php following the examples there for both CSS and java. I then put the js file into mytheme/scripts/ - and to be safe, also in themes/default/scripts
The FF inspector (debugger module) shows me that the script is there but it won't do anything. I get the follwoing error tooltip: "TypeError: spoiler is null", so I guess it doesn't find the class I'm looking for.

Any help is greatly appreciated! Oh, and Happy New Year everyone!

Chen Zhen


If this is for SMF 2.1 which includes JQuery support, you can use the following:

$(".inlineSP").on("click", function() {
  alert("My class was clicked! The index of it is: " + $(this).index());
});


My SMF Mods & Plug-Ins

WebDev

SMF support staff should be shaping a positive community experience & not provoking an argument or emotional reaction.

live627

The script   copuld  be running before the document loads. Put your entire spoiler  script inside a DOMContentLoaded event. https://developer.mozilla.org/en-US/docs/Web/API/Document/DOMContentLoaded_event

Julius_2000

#3
Quote from: live627 on January 07, 2025, 09:13:43 PMThe script  copuld  be running before the document loads. Put your entire spoiler  script inside a DOMContentLoaded event. https://developer.mozilla.org/en-US/docs/Web/API/Document/DOMContentLoaded_event
Thank you guys, you're fantastic! That helped me quite a bit.

Ok, so now with your great support here and my first time using CoPilot to guide me further, the inline spoiler works great!

You cannot view this attachment.

I can now click all spoilers and hide them again and also make links clickable only after they've been revealed.

Advertisement: