Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
14
rated 0 times [  17] [ 3]  / answers: 1 / hits: 18967  / 10 Years ago, thu, june 5, 2014, 12:00:00

I'm using the following JS I found online to implement a responsive navigation. There is nothing on the source about having any errors in IE8, however I'm doing some compatibility testing in BrowserStack (Win7+IE8) and getting the Object doesn't support this property or method error. Here is the entire script:



<script>
$(function() {
var pull = $('#menu');
menu = $('nav ul');
menuHeight = menu.height();

$(pull).on('click', function(e) {
e.preventDefault();
menu.slideToggle();
});
});

$(window).resize(function(){
var w = $(window).width();
if(w > 320 && menu.is(':hidden')) {
menu.removeAttr('style');
}
});
</script>


And this is the line that IE8 doesn't like (character 6 specifically):



if(w > 320 && menu.is(':hidden')) { 


Any help in solving this would be awesome, I'm still not the best at JS.


More From » jquery

 Answers
57

Just stop storing jQuery objects in globals at all. It doesn't cost much to just create them upon demand and you don't get into this lifetime/scoping issue that you had:



<script>
$(function() {
$('#menu').on('click', function(e) {
e.preventDefault();
$('nav ul').slideToggle();
});
});

$(window).resize(function(){
var menu = $('nav ul');
if($(window).width() > 320 && menu.is(':hidden')) {
menu.removeAttr('style');
}
});
</script>


Some general design/code layout thoughts that apply here:




  1. Avoid globals whenever possible.

  2. Don't declare something in one scope and then try to use it in another scope (won't work unless global so see rule #1) and if global may have timing issues too.

  3. Fetch selector results only when needed in the function where they are consumed. There is very, very rarely a reason to cache something like that beyond the lifetime of a function.

  4. If you are going to refer to the same jQuery object more than once within a function, then you may want to save it into a local variable for the duration of the function (as long as its results won't be modified within the function).


[#70700] Wednesday, June 4, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kaitlynnb

Total Points: 402
Total Questions: 96
Total Answers: 109

Location: Trinidad and Tobago
Member since Fri, May 8, 2020
4 Years ago
kaitlynnb questions
;