Jquery related css dropdown menu. Simple jQuery based dropdown menu


Also, if you are interested, you can look at previous way using the CSS that is described in the article -

Now to the point. As in the last article, first of all, let's write Html our menu code. The code is the same as in that article, so that there is no confusion and it is more understandable. A menu with two items and both have submenus.

If you have such a line or a similar one that has previously connected the library, then you should not do it again.

In the second line of the script, we indicate the ID of our menu. If you are using this way to your own menu, then naturally change the name to your own. IN this case This - #slow_nav.

You can also adjust the animation time. In this script, opening and closing costs 400 milliseconds, which is 0.4 seconds. If you want, you can change it to a higher value or to a smaller one.

The last step is adding styles. They are very similar to the styles from the previous article, only they are missing CSS properties animation.

#slow_nav> ul (width: 500px; margin: 25px auto 0;) #slow_nav> ul> li (list-style: none; display: inline-block; position: relative; padding: 0;) #slow_nav a (text- decoration: none;) #slow_nav> ul> li> a (font-size: 18px; padding: 5px; background-color: # 333; color: #fff;) #slow_nav li ul (position: absolute; list-style: none; text-align: center; top: 15px; font-size: 15px; left: 0; margin: 0; padding: 0; display: none;) #slow_nav li ul li (background-color: # 333; border- bottom: 1px solid # 888;) #slow_nav li ul li: last-child (border-bottom: none;) #slow_nav li ul li a (padding: 5px 12px; color: #fff; display: block;) #slow_nav li ul li: hover (background-color: # 444;) #slow_nav li ul li: first-child (margin-top: 25px; position: relative;) #slow_nav li ul li: first-child: before (content: "" ; position: absolute; width: 1px; height: 1px; border: 5px solid transparent; border-bottom-color: # 333; left: 10px; top: -10px;)

Also added to the styles one new line, with which the script works correctly. For element - #slow_nav li ul property set display: none;... If you do not add it, the drop-down menu will be initially visible and will disappear only after you move the cursor over it. All other styles are the same as in the previous article.

Like the previous method, this one can be applied not only to self-written menus but also to the same dynamic menus that are created by content management systems, for example WordPress... To do this, you need to tweak the styles a little and that's it. That is, you do not need to use the first HTML code, only styles. In styles, you need to replace the name of the id #slow_nav with what you will have, and it is possible to correct something else in detail. I will not dwell in detail. Each case requires a personal approach, so sorry 🙂

That's all, thank you for your attention. 🙂

In this article, we will develop a simple drop-down menu using jQuery. First take a look at the demo file. We hope you know at least a little of the basics of jQuery and CSS. The key aspects of creating this dropdown menu are applying the CSS parameters: position, top, left, z-index.

Using these options, we can be sure that our menu will appear exactly below the link that was hovered over and will exactly cover all other elements. We will also make the menu appear on hover, and disappear when the cursor is moved to the side. To implement these events, we will use jQuery's mouseenter and mouseleave functions. And that's all we need to create a dropdown menu!

Demo file of the final result and download link

HTML code

Check out the HTML for the dropdown menu:



As you can see, here we will use unordered lists to implement menu items. Each menu link is assigned a dropdown class, and the dropdown itself is encompassed by a sub-link class. The class names will be used by jQuery to determine which menu to display.

CSS code

Check out the CSS code:

/ * CSS For Dropdown Menu Start * /
ul
{
list-style: none;
padding: 0px;
margin: 0px
}

ul li
{
display: inline;
float: left;
}

ul li a
{
color: #ffffff;
background: # 990E00;
margin-right: 5px;
font-weight: bold;
font-size: 12px;
font-family: verdana;
text-decoration: none;
display: block;
width: 100px;
height: 25px;
line-height: 25px;
text-align: center;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border: 1px solid # 560E00;
}

ul li a: hover
{
color: #cccccc;
background: # 560E00;
font-weight: bold;
text-decoration: none;
display: block;
width: 100px;
text-align: center;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border: 1px solid # 000000;
}

ul li.sublinks a
{
color: # 000000;
background: # f6f6f6;
border-bottom: 1px solid #cccccc;
font-weight: normal;
text-decoration: none;
display: block;
width: 100px;
text-align: center;
margin-top: 2px;
}

ul li.sublinks a: hover
{
color: # 000000;
background: # FFEFC6;
font-weight: normal;
text-decoration: none;
display: block;
width: 100px;
text-align: center;
}

ul li.sublinks
{
display: none;
}

/ * CSS For Dropdown Menu End * /

Most of the CSS is used to format the menus (you can give appearance menu on your own), but there are also some important points here:

1 - Remove tabs with list-style: none;

2 - We know that lists are block elements and are always displayed vertically. In order to make them position horizontally, we give them an inline element parameter and align them to the left with the following code:

Display: inline;
float: left;

3 - Links are inline elements by default. We are converting them to block elements using display: block (so we can now give them a width value).

4 - We hide the entire menu by means of:

Ul li.sublinks
{
display: none;
}

jQuery

Imagine the old days when dropdown menus were implemented with a rough javascript code and a bunch of unnecessary code was needed. But today all we need is jQuery:

$ (function () (

Submenu.css ((
position: "absolute",

zIndex: 1000
});

Submenu.stop (). SlideDown (300);


$ (this) .slideUp (300);
});
});
});

A very interesting and simple thing. Let us explain to you how it works. To begin with, and as usual, we wrap our code in a jQuery controller:

$ (function () (
...
});

Our code is activated when the mouse cursor is hovering (mouseenter function) over an element that is assigned a dropdown class ($ (". Dropdown")). In our case, this is a link in the menu:

$ (function () (
$ (". dropdown"). mouseenter (function () (
........
});
});

Let's make sure we hide () all previously open menus before the mouse jumps to the next link:

$ (". sublinks"). stop (false, true) .hide ();

Pay attention to the stop function, which helps us to display only one drop-down menu at a time when the mouse cursor moves over different links in the menu. If we do not use this function, then each drop-down menu will remain open until the moment when we completely move the mouse cursor away from the menu. This will create some overlap, so we should avoid this. Next, we take the currently expanded dropdown and assign a variable:

Var submenu = $ (this) .parent (). Next ();

This is what will be in the HTML code:

When the mouse cursor is hovering over the link with the dropdown class, we move back using parent () and stop at "li", and then using next (), we find ourselves on the desired dropdown menu, and "li" will already be with the sub- links (sublinks). Thus, jQuery makes it easier for us to find out which dropdown to display when the mouse is over a specific link.

Submenu.css ((
position: "absolute",
top: $ (this) .offset (). top + $ (this) .height () + "px",
left: $ (this) .offset (). left + "px",
zIndex: 1000
});

The code is very important as it ensures that the dropdown is displayed exactly under the specified link. If the position is set to absolute, we can position the element anywhere on our page. Next, we define the top position of the link that the cursor is hovering over with $ (this) .offset (). Top (this refers to the current menu item that the cursor is hovering over), and add a height value to it so that the menu is displayed exactly below link. Do something similar with the left parameter. We then use z-index to make sure our menu is displayed on top of the rest of the elements.

Submenu.stop (). SlideDown (300);
Of course, you can use other animation options like fadeIn, animation with your own styles, and so on.

Now we need to distract from the concept of displaying the dropdown menu, and make it hide. We need the following piece of code:

Submenu.mouseleave (function () (
$ (this) .slideUp (300);
});

To hide the dropdown menu, we use slideUp, which is the opposite of slideDown. Keep in mind that submenu is a variable that we created to define a specific dropdown menu.

Thus, we have an attractive sibling dropdown jQuery menu.

In order to write navigation in the form of a vertical drop-down menu in jQuery with a drop-down list of subcategories, you need to understand the very principle of this mechanism. But first, let's take a look at the navigation structure:

Navigation

Navigation

As you may have guessed, our dropdown menu is built around bulleted lists. On hovering over a tag

everything that is included in it will be revealed, namely:

  • test 1
  • test 2
  • test 3
  • test 4

But how, you ask? Yes, everything is actually very simple. First, let's take a look at our nav list stylesheet, which looks like this:

Body (background: rgb (244, 244, 244); font-family: Verdana; font-weight: 100;) / * --- Navigation --- * / #menu (width: 200px; margin: 0; padding: 2px;) #menu li (list-style-type: none;) .menu (position: relative; background: chocolate; background: -moz-linear-gradient (top, rgb (198, 255, 242), # 2AC4B3) ; background: -webkit-linear-gradient (top, rgb (198, 255, 242), # 2AC4B3); background: -o-linear-gradient (top, rgb (198, 255, 242), # 2AC4B3); border : 1px solid # 2AC4B3;) .menu: hover (background: # 00c; background: -moz-linear-gradient (top, rgb (230, 230, 230), # 0CBFAB); background: -webkit-linear-gradient ( top, rgb (230, 230, 230), # 0CBFAB); background: -o-linear-gradient (top, rgb (230, 230, 230), # 0CBFAB);) .menu span (width: 11px; height: 11px; display: block; position: absolute; top: 8px; right: 10px; cursor: pointer;) .menu ul (width: 150px; margin: 0; padding: 1px; position: absolute; top: -1px; left: 198px;) .menu ul li (background: chocolate; background: -moz-linear-gradient (top, rgb (198, 255, 242), # 2AC4B3); background: -webkit-linear-gradient (top, rgb (198, 255, 242), # 2AC4B3); background: -o-linear-gradient (top, rgb (198, 255, 242), # 2AC4B3); border: 1px solid #fff; ) .menu ul li: hover (background: # 00c; background: -moz-linear-gradient (top, rgb (230, 230, 230), # 0CBFAB); background: -webkit-linear-gradient (top, rgb ( 230, 230, 230), # 0CBFAB); background: -o-linear-gradient (top, rgb (230, 230, 230), # 0CBFAB);) .menu a (padding: 5px; display: block; text- decoration: none; color: white;) .menu a: hover (color: white;) / * --- END --- * /

From the style sheet, you can see that the dropdown is not initially hidden, but we will correct this point with:

$ (document) .ready (function () ($ (". menu ul"). hide (); $ (". menu span"). css ("background", "url (" down.png ")") ; $ ("# menu li"). hover (function () ($ (this) .children ("ul"). show (); / * Equivalent to $ ("ul", this) .show (); * / $ (this) .find ("span"). css ("background", "url (" right.png ")"); / * Equivalent to $ ("span", this) .css ("background", "url ("right.png") "); * /), function () ($ (this) .children (" ul "). hide (); / * Equivalent to $ (" ul ", this) .hide (); * / $ (this) .find ("span"). css ("background", "url (" down.png ")"); / * $ ("span", this) .css ("background", " url ("down.png") "); * /))))

Now let's take a closer look at the jQuery dropdown menu code, because perhaps it will not be quite clear to someone. At the very beginning, the following construction is written:

$ (document) .ready (function () ())

It contains commands that must be executed after the page is fully loaded. This is done so that all sorts of errors do not appear, if it is impossible to find any object due to the fact that it has not yet been trivially loaded.

$ (". menu ul"). hide ();

What does this entry mean? The "$ ()" construction allows you to select items. Therefore, at the very beginning, we need to hide our dropdown list. We take the "$ ()" construction and write the object of interest to it. In our case, this object will be bulleted list with the class "menu". Next, we write the "hide ()" method, which allows us to hide the object of interest to us.

$ (". menu span"). css ("background", "url (" down.png ")");

What she does? She is looking for a tag parent element which is assigned the class "menu" and, using the method "css (" background "," url ("down.png") ")", the property of the style "background" is assigned the value "url (" down.png ")". "down.png" is an icon indicating that the list can be expanded.

Then comes the construction, which will expand our list, it looks like this:

$ ("# menu li"). hover (function () ($ (this) .children ("ul"). show (); $ (this) .find ("span"). css ("background", " url ("right.png") ");), function () ($ (this) .children (" ul "). hide (); $ (this) .find (" span "). css (" background " , "url (" down.png ")");)

We are looking for a tag whose parent element is assigned id = "menu." Next comes the "hover" method and two functions in parentheses. The first function will be executed when the mouse cursor is hovering, and the second will be executed if the mouse cursor leaves the element of interest.

The first function says:

$ (this) .children ("ul"). show (); $ (this) .find ("span"). css ("background", "url (" right.png ")");

The construction "$ (this)" means that we are interested in the element to which we are in this moment hovered (this from English this). And we hovered over the tag

... Next, using the "children (" ul ")" method, we search for the nested tag from the tag and display it using the "show ()" method.

After that, we are looking for descendants of the tag, namely: the tag and we change the background for it to another icon.

After that, a function is written that does everything as it was originally, after the mouse cursor leaves the list item:

Function () ($ (this) .children ("ul"). Hide (); $ (this) .find ("span"). Css ("background", "url (" down.png ")"); )

For the written jQuery code to work and our drop-down menu to work correctly, you need to download the library from the jquery.com website and connect it by writing it after the opening tag string.

That's it! In conclusion, I want to note that if your site is quite weighty, then perhaps the script will be launched too late (the site will take a long time to load) and users will see how it first opens up completely, and only then hides, which, you see, is very ugly. Therefore, it is necessary to move all jQuery commands for this construction: "$ (document) .ready (function () ())". It will look like this:

$ (document) .ready (function () ()) $ (". menu ul"). hide (); $ (". menu span"). css ("background", "url (" down.png ")"); $ ("# menu li"). hover (function () ($ (this) .children ("ul"). show (); $ (this) .find ("span"). css ("background", " url ("right.png") ");), function () ($ (this) .children (" ul "). hide (); $ (this) .find (" span "). css (" background " , "url (" down.png ")");))

Connecting our script needs to be transferred from the tag to the very end, before the closing tag, or you can include the script right after the bulleted list.

(Downloads: 314)

With the help of the classic jQuery, a ton of articles have been written on this topic. I tried to complicate the task a little by adding the ability to keep menu sections open (or closed, depending on the user's choice) while navigating the site.
To solve this problem, I decided to use the jQuery Cookie plugin. The advantage of this plugin is that the operation is performed on the client side, which, in turn, reduces the load on the server. Minus - if the user has JS disabled, the plugin will not work. But this option I do not consider, since then the whole meaning of the drop-down menu disappears altogether. So, let's begin.
First, we need to connect the jQuery framework itself and the jQuery Cookie plugin:

Code: HTML





Next is the markup. It will look like a simple list, nothing supernatural. The only thing to note is that in the tag

there should be a title, when you click on which the menu will drop out:

Code: HTML


And so on ad infinitum. Now comes the fun part. I'll add a few comments in the code to make it roughly clear, chopach

Code: JS

$ (document) .ready (function () (
if ($. cookie ("num_open_ul")) (// checked if there is an entry in cookies
if ($. cookie ("num_open_ul")! = 0) (// and this entry is not equal to 0
var number_eq = parseInt ($. cookie ("num_open_ul") - 1);
$ (". navigation_body"). eq (number_eq) .show (). prevAll ("# navigation h2.navigation_head: first"). addClass ("active_navigation");
}
};
$ ("# navigation h2.navigation_head"). click (function () (// when clicked this function will be triggered
if (! $ (this) .next (). is (": visible")) (
$ ("div.navigation_body"). siblings ("div.navigation_body"). slideUp (500); // if others are open, close everything except the current one
}
$ (this) .next ("div.navigation_body"). slideToggle (500) .siblings ("div.navigation_body"). slideUp (500);
$ (this) .toggleClass ("active_navigation"). siblings ("# navigation h2.navigation_head"). removeClass ("active_navigation"); // added a class to the public to change the style
setTimeout (fncookie, 600); // writing to cookies itself with a delay, so that the script has time to complete the work before recording (500ms - speed, delay - 600ms)
});
function fncookie () (// the write function itself
var number_open_ul = 0;
var i = 0;
$ ("div.navigation_body"). each (function () (
i ++;
if ($ (this) .is (": visible")) (
number_open_ul = i;
}
$ .cookie ("num_open_ul", number_open_ul, (expires: 3, path: "/")); // keep 3 days for the whole site.
});
}
});


That is, now, if the user opened the menu, left the site and went to it again after a couple of days, the menu will still remain open for him.
And finally, we have a little touch left: in fact, css- styles... Do it to your taste, in the example I took finished design from one of the projects

Code: CSS

#navigation (
margin: 80px auto;
width: 250px;
}
#navigation h2, #navigation h2.navigation_head (
font-size: 18px;
font-weight: bolder;
background-color: # ffb6c1;
background-image: -webkit-gradient (linear, 50% 0.50% 100%, color-stop (0%, # ffe9e9), color-stop (100%, # ffb6c1));
background-image: -webkit-linear-gradient (# ffe9e9, # ffb6c1);
background-image: -moz-linear-gradient (# ffe9e9, # ffb6c1);
background-image: -o-linear-gradient (# ffe9e9, # ffb6c1);
background-image: linear-gradient (# ffe9e9, # ffb6c1);

padding: 5px 3px 6px 3px;
margin: auto;
position: relative;
}
#navigation h2.navigation_head: after (
position: absolute;
right: 5px;
color: # 550000;
content: "cssb";
}
#navigation h2: hover, #navigation h2.navigation_head: hover (
cursor: pointer;
}
.active_navigation (
background-image: -webkit-gradient (linear, 50% 0.50% 100%, color-stop (0%, # ffb6c1), color-stop (100%, # ffe9e9))! important;
background-image: -webkit-linear-gradient (# ffb6c1, # ffe9e9)! important;
background-image: -moz-linear-gradient (# ffb6c1, # ffe9e9)! important;
background-image: -o-linear-gradient (# ffb6c1, # ffe9e9)! important;
background-image: linear-gradient (# ffb6c1, # ffe9e9)! important;
}
.active_navigation: after (
position: absolute;
right: 5px;
content: "cssd"! important;
}
.navigation_body (
display: none;
}
#navigation ul (
margin: 0;
padding: 0;
list-style-type: none;
}
* html #navigation ul li (
height: 1%;
}
#navigation div.navigation_body ul li (
margin-left: 10px;
}
#navigation a (
font-family: "Times New Roman";
display: block;
color: # 918871;
padding: 3px;
background-color: # ffe3e0;
border-bottom: 1px solid #fff;
text-decoration: none;
}
#navigation a: hover (
color: # 585858;
background-color: # ffb6cc;
}


If anyone noticed, here I tried using the content: +/- property when closed / open menu, but you can add an image or any other design. You can see an example of what we got here.

As always, I am ready to listen to questions and try to answer them. All the best, all the best.

In this tutorial, we'll show you how to create a side dropdown menu for even easier site navigation. This menu is a popular trend in modern web design. Many sites use this type of menu. With its help, you can get rid of the chaos on the project pages, make it more readable, focusing users' attention on the main content.

It's a great way to achieve minimalism without distractions. Today we will create such a menu ourselves.

To create a navigation menu, let's first take a look at the settings:

Animation Menu Demo

First you need to load Normalize.css and set up the default browser styles to make sure the menu looks the same across all browsers. We'll use FontAwesome to display an arrow in front of menu items with sub-items. To switch classes in the menu, load jQuery and move all custom jQuery code to script.js. The last link is the main table for the web project.

Hamburger icon

The hamburger icon is a common site navigation attribute. It is often created using an icon font such as FontAwesome, but in this tutorial we will add some animation so we will create it from scratch. Our hamburger icon is a span tag containing three class divs, displayed as horizontal bars.

The styles look like this:

Toggle-button (position: fixed; width: 44px; height: 40px; padding: 4px; transition: .25s; z-index: 15;) .toggle-button: hover (cursor: pointer;) .toggle-button .menu -bar (position: absolute; border-radius: 2px; width: 80%; transition: .5s;) .toggle-button .menu-bar-top (border: 4px solid # 555; border-bottom: none; top: 0;) .toggle-button .menu-bar-middle (height: 4px; background-color: # 555; margin-top: 7px; margin-bottom: 7px; top: 4px;) .toggle-button .menu-bar -bottom (border: 4px solid # 555; border-top: none; top: 22px;) .button-open .menu-bar-top (transform: rotate (45deg) translate (8px, 8px); transition: .5s; ) .button-open .menu-bar-middle (transform: translate (230px); transition: .1s ease-in; opacity: 0;) .button-open .menu-bar-bottom (transform: rotate (-45deg) translate (8px, -7px); transition: .5s;)

The icon has a fixed position and does not change when scrolling the page. Also has a z-index of 15, which means it will always be on top of other elements. Consists of three bars, each of which shares other styles. Therefore, we will move each bar to the .menu-bar class. Move the rest of the styles to separate classes... The magic happens when we add another class to the span tag that is public. We add it with using jQuery in the following way:

$ (document) .ready (function () (var $ toggleButton = $ (". toggle-button"); $ toggleButton.on ("click", function () ($ (this) .toggleClass ("button-open" );));));

For those unfamiliar with jQuery, we initialize a variable with $ toggleButton that contains our icon. We store it in a variable unnecessarily using JavaScript... Then we create an event listener that takes into account the clicks on the icon. Every time the user clicks on the hamburger icon, the event listener fires the toggleClass () function, which toggles the .button-open class.

With the .button-open class added, we can use it to change how elements are displayed. We use the CSS3 translate () and rotate () functions to make the top and bottom stripes rotate 45 degrees and the middle stripe to shift to the right and disappear. Here's the animation you can customize:

Dropdown navigation menu

Now that you have your hamburger icon, let's make it useful and create a dropdown menu when you click on it. This is how the menu markup looks like:

We will not go into detail on each style for this menu now, instead we will focus on a few important points... First of all, it's a div and a .menu-wrap class. Take a look at his styles:

Menu-wrap (background-color: # 6968AB; position: fixed; top: 0; height: 100%; width: 280px; margin-left: -280px; font-size: 1em; font-weight: 700; overflow: auto ; transition: .25s; z-index: 10;)

The position is fixed, so when scrolling the page, the menu always stays in one position. A height of 100% allows the menu to take up all the vertical space on the page. Note that the margin-left is set to a negative number equal to the width of the menu. This means that the menu will disappear from the viewport. To make it visible again, we create another toggler class with jQuery. Our JavaScript file will look like this:

$ (document) .ready (function () (var $ toggleButton = $ (". toggle-button"), $ menuWrap = $ (". menu-wrap"); $ toggleButton.on ("click", function () ($ (this) .toggleClass ("button-open"); $ menuWrap.toggleClass ("menu-show");));));

Add another $ menuWrap variable that contains the menu wrapper. Use the same event handler we created earlier. Only this time, we toggle two classes: one for the button and one for the menu shell. The left margin of the .menu-show class is 0, this will add a drop shadow effect.

Menu-show (margin-left: 0; box-shadow: 4px 2px 15px 1px # B9ADAD;)

Submenus and links

You may notice that one of the list items has a class .menu-item-has-children which contains a submenu. In addition, just below the link is a span tag with the .sidebar-menu-arrow class.

span has :: after pseudo-element and contains a FontAwesome arrow. By default, the submenu is hidden and will only be visible when you click on the arrow. This is how we can do it with jQuery:

$ (document) .ready (function () (var $ sidebarArrow = $ (". sidebar-menu-arrow"); $ sidebarArrow.click (function () ($ (this) .next (). slideToggle (300); ));));

When we click on the arrow, we call a function, which in turn targets the next element immediately after the span (in our case, it's a submenu) and makes it visible. The function we are using is slideToggle. It makes the element appear and disappear. The function in our example has one parameter - the duration of the animation.

The menu items in the example have a hover effect. It is created using :: after pseudo-element. The code looks like this:

Menu-sidebar li> a :: after (content: ""; display: block; height: 0.15em; position: absolute; top: 100%; width: 102%; left: 50%; transform: translate (-50% ); background-image: linear-gradient (to right, transparent 50.3%, # FFFA3B 50.3%); transition: background-position .2s .1s ease-out; background-size: 200% auto;) .menu-sidebar li > a: hover :: after (background-position: -100% 0;)

The :: after pseudo-element contains a block level element at the bottom of each link with a full width and height of 0.15em. It all looks like an underline. The peculiarity is that we are not just applying the background color to the line, we are using the linear-gradient () function on the background image. Although this function is for creating color gradients, we can change the color by specifying the percentages we want.

Menu-sidebar li> a :: after (background-image: linear-gradient (to right, transparent 50.3%, # FFFA3B 50.3%);)

Half of the line is transparent and the other half is yellow. By making the background size 200%, we double the width of our box. Now the transparent part takes up the entire width of the link, and the yellow part moves to the left and becomes invisible. We change the position of the background on hover by -100%. The yellow part is now visible and the transparent part is hidden.

You can use any other color instead of the transparent part. You can also experiment with gradients.

Each of the elements we have considered works as a whole. You can create such a menu using any site design from the TemplateMonster collection. As you can see, doing this is easier than you might imagine. Good luck creating professional and user-friendly websites!