How can I achieve the following?
// Resize triggers
$(window).resize(function() {
if (window.innerWidth <= 480) {
$('#menu-primary-navigation').wrapInner('<li id="menu" class="dd"><ul class="sub-menu"></ul></li>');
$('#menu').prepend('<a href="#">Menu</a>');
}
if (window.innerWidth >= 480) {
// Remove the above .wrapInner & .prepend()
}
}) .resize();
UPDATE:
This is what I have without the resize events, but I’d like to remove the .wrapInner and .prepend code when the screen is less than 480px wide.
Try this:
Note I added
&& !$('#menu').length. This is to only add the menu if it doesn’t already exist. You can also put the secondifas anelse, as they are mutually exclusive. (when you change the>= 480to> 480)Demo Code: http://jsfiddle.net/jtbowden/WzweR/
Demo (full screen): http://jsfiddle.net/jtbowden/WzweR/embedded/result/
Also, I don’t think you can end up with valid markup. Either you are wrapping non-
liitems in aul, or you are adding aainside of aul… But maybe I haven’t thought through what your markup looks like. I am just guessing. And I am assuming you are collapsing part of your menu structure if the window is too narrow.Update:
After seeing your code, a couple of changes. First I was missing a
>in myreplaceWith($('#menu > ul').children());. That makes a big difference, as you don’t want to pull all of theuls out of context. Second, you are adding some stuff to your links, which you need to do in your resize call:You will also need to change your
.click()handler to a.on()call, because your elements are being created dynamically. When they are removed, any click handlers are removed. If you use.on()you essentially attach the handler to a higher element in the DOM tree and filter on the element you want to respond:Demo Code: http://jsfiddle.net/jtbowden/9fHPA/7/
Demo (full screen): http://jsfiddle.net/jtbowden/9fHPA/7/embedded/result/