Problem with jQuery

I’ve been creating an animated div-menu, and then clicking on the button to close it I add the closing class.

.closeMenu {
  visibility: hidden;
  opacity: 0;
  transition: visibility 0s linear 0.33s, opacity 0.33s linear;

I am doing this through jQuery.

jQuery("#closeDiv").on("click", function(event) {

It doesn’t work though.

Twine Version: Twine 2
Story Format: Sugarcube 2

I’m not at my laptop so I can’t try this out right now but I think your problem is that event.parentElement is a native DOM object and addClass is a jQuery method. So you want to do it either through the DOM with event.parentElement.classList.add(), or with jQuery with $(this).addClass(). I think.

1 Like

Unfortunately that didn’t work either, I don’t understand what’s going on, in theory the code is correct…

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:


I’m guessing you were trying to do this instead:


However, you can shorten that to this:


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:

	$(document).one(":passagerender", function (event) {
		$(event.content).find("#closeDiv").on("click", function (event) {

(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! :grinning: