This is my first jquery, I'm writing code following a tutorial (not a jquery tutorial, so there was no help for this issue) but want to understand what is happening better because there are a lot of new layers. The original code is re-written by babel so I'm not sure if it is because a new standard has made this code not work in modern browsers:
Original code:
import $ from 'jquery';
class MobileMenu{
constructor() {
this.menuIcon = $(".site-header__menu-icon");
this.menuContent = $("site-header__menu-content");
this.events();
}
events() {
this.menuIcon.click(this.toggleTheMenu.bind(this));
}
toggleTheMenu() {
console.log(this.menuContent);
this.menuContent.toggleClass("site-header__menu-content--is-visible");
}
}
export default MobileMenu;
Babel created code:
var MobileMenu = function () {
function MobileMenu() {
_classCallCheck(this, MobileMenu);
this.menuIcon = (0, _jquery2.default)(".site-header__menu-icon");
this.menuContent = (0, _jquery2.default)("site-header__menu-content");
this.events();
}
_createClass(MobileMenu, [{
key: "events",
value: function events() {
this.menuIcon.click(this.toggleTheMenu.bind(this));
}
}, {
key: "toggleTheMenu",
value: function toggleTheMenu() {
console.log(this.menuContent);
this.menuContent.toggleClass("site-header__menu-content--is-visible");
}
}]);
return MobileMenu;
}();
exports.default = MobileMenu;
It returns:
[prevObject: jQuery.fn.init(1)]
length:0
prevObject:[document]
__proto__:Object(0)
instead of my expected class that I want to perform an action on.
Below is the snippet of html that contains the class, I've checked for typos in the name and didn't find very much helpful information when I googled for why jQuery returns init(1) and length:0. I found: Why is my JQuery selector returning a n.fn.init[0], and what is it? but it seemed very specific to that instance and I was hoping for more general information. I'm not doing dynamic page loads. From that question though I gather that my jquery is returning an empty result object. Is that a correct understanding and what should I check first in my debugging? I set a breakpoint in chrome debugger but still just got the object but with two elements in the array with the first element being the object I clicked on to trigger the jquery.
<div class="site-header__menu-icon"></div>
<div class="wrapper site-header__menu-content">
<a href="#" class="btn site-header__btn">Get in Touch</a>
<nav class="primary-nav primary-nav--pull-right">
<ul>
<li><a href="#our-beginning">Our Beginning</a></li>
<li><a href="#features">Features</a></li>
<li><a href="#testimonials">Testimonials</a></li>
</ul>
</nav>
</div>
</div>
Here is the babel module:
module: {
loaders: [
{
loader: 'babel-loader',
query: {
presets: ['es2015']
},
test: /\.js$/,
exclude: /node_modules/
}
]
}