• I want to implement custom function when user changes Device in Device preview dropdown in top toolbar in editor. Previously, I used regular js to detect button click but latest update changed this area to Dropdown and it has no specific classes that can be tracked. Is any hook to do this job?

Viewing 3 replies - 1 through 3 (of 3 total)
  • Moderator bcworkz

    (@bcworkz)

    I suggest using jQuery to implement click event listeners. Then you can use typical CSS selectors. For example:

    $( ".block-editor-post-preview__dropdown-content .components-menu-item__button" ).on( "click", function() {
      /* do somthing */
    } );

    Something similar can be done with straight JS by “walking the DOM” down through its nodes, but jQuery is simpler and it’s loaded on the editor page anyway.

    You probably already know that the preview dropdown is not an actual HTML select/option field dropdown, but actually a series of buttons made to look and operate like a traditional dropdown. I found it interesting and worth mentioning all the same ??

    Thread Starter wpsoul

    (@wpsoul)

    @bcworkz this is exactly what I used before, it doesn’t work now because dropdown is replaced by Dropdown component and it creates dropdown dynamically when you open it. Problem here is that WP team didn’t add any unique classes to this dropdown so I can’t detect clicks precisely for this part

    Moderator bcworkz

    (@bcworkz)

    it creates dropdown dynamically when you open it

    In that case unique classes will not be useful because when your add listener script runs those elements will not yet exist. You really would need some kind of hook tied to the element creation script to ensure the elements exist before adding a listener. I’m unsure if such a thing exists.

    Here’s a thought, no idea if it’d work though — add a listener to the preview icon itself. That callback would then insert a script node that would add listeners for clicks on the actual elements. The idea being by the time your script node is inserted and runs, the dropdown elements would have already been inserted as well. Of course now unique classes would be useful, but your callback does have this, the element actually clicked on. You could get all child elements of this‘s parent and work out the index number of which child is this.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Custom hook on device preview change’ is closed to new replies.