There isn’t quite enough information there to tell exactly what you’re doing, and event.parentElement.addClass('closeMenu');
isn’t valid code, but I’m guessing that the “#closeDiv” element doesn’t exist in the document yet at the point where you’re making that jQuery call.
SugarCube first renders the passage to a “virtual” context, at which point code in the passage is triggered, and after that it adds the passage content to the document. If that jQuery call is being made while the passage is still “virtual”, then it won’t be able to find the element in the document, since it isn’t there yet.
First, looking at this earlier code you gave:
event.parentElement.addClass('closeMenu');
I’m guessing you were trying to do this instead:
$(event.target.parentElement).addClass('closeMenu');
However, you can shorten that to this:
$(this).parent().addClass('closeMenu');
For what I think you’re trying to do, it would be simpler to implement that code like this:
<div id="closeDiv" onclick="$(this).parent().addClass('closeMenu')">...</div>
(See the jQuery .parent() and .addClass() methods for details on how those work.)
Due to the “onclick” attribute, clicking on that div triggers the jQuery code which adds the “closeMenu” class to the div’s parent.
Alternately, if you wanted code which would work on the passage while it’s still “virtual”, you could put something like this in your passage instead:
<<script>>
$(document).one(":passagerender", function (event) {
$(event.content).find("#closeDiv").on("click", function (event) {
$(this).parent().addClass("closeMenu");
});
});
<</script>>
(See the SugarCube :passagerender event and the jQuery .one(), .on(), and .find() methods.)
That waits for the :passagerender event for this passage, and then uses event.content to access the “virtual” context the passage is being rendered to, where it can now attach the “click” event handler to the div that will add the “closeMenu” class to the div’s parent element when triggered.
Hope that helps!