Streaming live at 10am (PST)

Set dropdown initial state to open


#1

Hi,

I’m trying to have the initial state of a dropdown set to open. I was able to get the desired behaviour by setting an initial state on the menu itself to display: block; however that created a problem where a user would be required to click twice on the dropdown to close it the first time around.

So my second line of thought was to simulate a click on the dropdown toggle itself but that doesn’t seem to work either. Here’s the code I’ve been using:

<script>
$(document).ready(function() {

  // Tried this hoping to bypass jQuery to make sure the element would receive the event
  document.getElementById('product-details').click();

  // Tried these 2 as well using jQuery
  $('#product-details').trigger('click');
  $('#product-details').click();
 
  // Tried to fire the click on the text block inside the dropdown hoping it would bubble through.
  $('.text-block-11').click();
};
</script>

Any other hacks to make this happen? I thought maybe setting a class to open on the dropdown using the first method?

Figured I’d check in here see if anyone ever came up with a good solution before I spend more time hacking at this.

Thanks.


#2

Found a solution. It’s not exactly pretty but it works. Seems like the dropdown component doesn’t care about the click event and relies instead on the mouse up / mouse down events:

<script>
    var dropdown = document.querySelector('.dropdown-toggle'); 
    
	triggerMouseEvent(dropdown, 'mousedown');
	triggerMouseEvent(dropdown, 'mouseup');

	function triggerMouseEvent (node, eventType) {
      var clickEvent = document.createEvent('MouseEvents');
      clickEvent.initEvent(eventType, true, true);
      node.dispatchEvent(clickEvent);
	}
</script>

I have attempted to convert this to JQuery using the node.trigger(‘mousedown’) followed by node.trigger(‘mouseup’) methods on the node as well as node.mousedown() followed by node.mouseup() and it didn’t work. So the vanilla Javascript code up there is the only way to accomplish that as far as I can tell.

Insert in the ‘Before </body> tag’ part in your page settings and enjoy :slight_smile:


#3

You can reduce all of that code to

$('.dropdown-toggle').trigger('tap');

#4

Where were you all my life? Thanks!