Variable indéfinie

Par heb, il y a 2 ans


Bonjour,
Ce script permet d'accèder à une partie de la page via une ancre..

$(window).on("scroll", function() { $('.navbar-nav span').each(function() { var headerHeight =$('header').outerHeight(); var scrollPos = $(document).scrollTop(); var linkRef = $($(this).attr("data-ancre")); var refPos = linkRef.offset().top - headerHeight; var refHeight = linkRef.height(); if(refPos <= scrollPos && refPos + refHeight > scrollPos){ $('li span').removeClass("active-yes"); $(this).addClass("active-yes"); } else { $(this).removeClass("active-yes"); }; }); });

Que j'utilise comme ceci :

<span data-ancre="#creation" title="">Mon lien</span> // et renvoie à <div id="creation">bla</div>

Le problème est que cette fonction est dans monfichier.js
Si je n'utilise pas la page où se situe <div id="creation"> j'obtiens :

Uncaught TypeError: Cannot read properties of undefined (reading 'top') at HTMLSpanElement.<anonymous> (advisto.js:1093:32) at Function.each (jquery.js:2:2573) at w.fn.init.each (jquery.js:2:1240) at monfichier.js:1089:24 at dispatch (jquery.js:2:41772) at y.handle (jquery.js:2:39791)

Merci

3 réponses

Soundboy39, il y a 2 ans

Hello,

est-ce que "linkRef" existe bien ?

heb, il y a 2 ans

non pas toujours

Grafikart, il y a 2 ans

Donc met une condition ici, si linkRef n'existe pas (est null) alors tu return plus tôt pour ne pas continuer le code.