Sanction Sanction - 4 months ago 19
jQuery Question

Initialise an element with a function dynamically - jQuery

I'm currently using react router to build my site, but I have

.dropdown
s on several pages which I initialise using
$('.dropdown').dropdown();


How can I keep initialising my dropdowns on every page I visit using react router? The
onhashchange
doesn't seem to register the URL changing.

This is what my dropdown function looks like.

jQuery

$(function() {
$('.dropdown').dropdown();
$(window).on('hashchange', function(e){
$('.dropdown').dropdown();
});
});

$.fn.extend({
dropdown: function(o){
var o = $.extend({ maxHeight: 600, buffer: 100, delay: 500 }, o);

return this.each(function(){
var dropdown = $(this),
toggle = dropdown.find('.toggle'),
menu = dropdown.find('.menu'),
a = dropdown.find('a'),
liheight = dropdown.height();
if(!dropdown.length){ return; }


toggle.click(function(e){
if(!menu.is(':visible')) {
$('.menu').parent().removeClass('open');
}
menu.parent().addClass('open');
});

$(document).bind('click', function(e){
if (! $(e.target).parents().hasClass('dropdown'))
menu.parent().removeClass('open');
});
});
}
});


I have also tried this, but still no luck:

$('body').on('focus', '.dropdown' function(e){
$('.dropdown').dropdown();
});


Edit: The solution

Used the
componentDidMount()
function in react router to initialise the dropdown every time the dropdown was rendered. This is what I added:

export const elDropdown = React.createClass({
componentDidMount: function() {
$(document).ready(function() {
$('.dropdown').dropdown();
})
},
render() {
return(
<div>...

Answer

you need to initialise the dropdowns after they become available on the page. The right place to do that is in React's lifecycle methods. In that case, componentDidMount - https://facebook.github.io/react/docs/component-specs.html#mounting-componentdidmount

You can create a component that wraps the dropdown and initialises it. Here is a simple example of how you could achieve that:

class DropdownWrapper extends React.Component {
  constructor(){
    super()
    this.id = 'someUniqueID'
  }
  componentDidMount(){
    $('#' + this.id).dropdown();
  }
  render(){
    return <select id={this.id} otherProps={this.otherProps} ></select>
  }
}

Notice that you will need to use unique identifiers. You can pass it to the component manually or create it randomly.

Comments