J'essaie de développer un menu de navigation réactif qui crée dynamiquement un élément de menu «Plus ...» lorsque la taille de l'écran est inférieure à une certaine largeur.Requête multimédia basée sur Javascript
Heres mon code à ce jour:
Html:
<ul id="menuElem" class="clearfix">
<li class="HighLighted"><a href="#">Menu Item 1</a></li>
<li><a href="#">Menu Item 2</a></li>
<li><a href="#">Menu Item 3</a></li>
<li><a href="#">Menu Item 4</a></li>
<li><a href="#">Menu Item 5</a></li>
<li><a href="#">Menu Item 6</a></li>
</ul>
Javascript:
function MoreMenu() {
//Checks if sub-menu exsists
if ($(".sub-menu").length > 0) {
//if it does then prepends second-last menu item to sub menu
$(".sub-menu").prepend($("#menuElem > li:nth-last-child(2)"));
}
else {
//if it doesn't exsist then appends a list item with a menu-item "more" having a sub-menu and then prepends second-last menu item to this sub menu.
$("#menuElem").append("<li class='more'><a href='#'>More...</a><ul class='sub-menu'></ul></li>");
$(".sub-menu").prepend($("#menuElem > li:nth-last-child(2)"));
}
}
function RemoveMoreMenu() {
//checks if sub-menu has something
if ($(".sub-menu li").length > 0) {
//if it does then the first child is taken out from the sub-menu and added back to the main menu.
$(".sub-menu li:first-child").insertBefore($("#menuElem > li:last-child"));
//if sub-menu doesn't have any more children then it removes the "more" menu item.
if ($(".sub-menu li").length === 0) {
$(".more").remove();
}
}
}
function Resize() {
benchmark = 800; //Maximum width required to run the function
$(window).resize((function() {
currentWidth = $(window).width(); //Current browser width
if (benchmark - currentWidth > 0) {
//checks if the browser width is less than maximum width required and if true it trigers the MoreMenu function
MoreMenu();
console.log("screen size resized down");
}
else {
}
}));
}
Le problème est quand je lance la fonction Resize()
il fonctionne en fait fonction MoreMenu()
pour chaque redimensionnement de la fenêtre activité qui est inférieure à 800px - ce qui n'est pas idéal.
Alors, est-il possible d'exécuter cette fonction MoreMenu()
une seule fois lorsque la taille de l'écran passe sous 800?
Merci à l'avance -Struggling pour obtenir ma tête javascript :)