Dynamic menu. Dynamic drop-down menu. Changing a Menu Class Using jQuery
Abstract: Purpose. Learn to apply HTML elements(lists and hyperlinks), and CSS properties(display model, hyperlink pseudo-classes) to form a navigation system on a web page.
Placing a menu with a set of hyperlinks on a page is one of the important tasks in the practice of a web designer. In order not to tire the user's attention by viewing the entire set, links are usually grouped into categories, and only categories are included in the main menu. Only when you select a category should the corresponding links (or subcategories) be displayed.
As a rule, such dynamic menus are usually created using Javascript language, which allows you to perform manipulations with elements of a web page of any complexity. However, there is also a CSS solution - quite simple and beautiful, although it does not fulfill every designer’s imagination. Let's look at it step by step.
- Popular dishes
- Italian Cuisine
- Snacks
- Snacks
- Sweets
- Fruits
- Gifts for the holiday
- Anniversaries
- For kids
- Birthday
- Congratulations!!!
- Choice by price
- Less than 1000 rub.
- From 1000 to 1500 rubles
- From 1500 to 2000 rubles
- From 2000 to 3000 rubles
- Expensive
- Fruits and vegetables
- Dried Fruits and Nuts
- Fruit baskets
- Mountains of fruits
- Healthy food
- No pesticides
- Flowers
- Natural flowers
- garden flowers
- "Talking" flowers
- Corporate gifts
Come up with the names of links and categories yourself. It is important that the id attribute external list had the value MainMenu - then it will be assigned a special style based on this identifier).
#MainMenu > li ( float: left; list-style-type: none; )
Monitor changes to your document's display by splitting the editor window into a view source code and designer. After applying the specified style rule, the outer list items ( li ) were positioned horizontally (due to wrapping):
Rice. 7.1.
#MainMenu li:hover ul ( display:block; )
Save the document you are developing, open it in a browser and make sure that the menu works correctly.
- Assign anchors of any nesting level in the menu (rule #MainMenu a ) the desired color (color), typeface (font), and also remove the underline (text-decoration).
- Assign list items to categories (rule #MainMenu > li ) background color(background), padding(padding) and a frame on the right (border-right).
- Give the nested link list items (rule #MainMenu li li ) the same background color as the category list, and small indentation and a frame at the bottom. Also, remove the list markings (list-style-type ).
- Remove margins and padding from the list of links (rule #MainMenu li ul ).
A small problem is that some category list items increase in width when you hover over them. This is because the width of a list element is determined by the width of the entire content - including the nested list. However, if you throw the nested list out of the normal flow and position it absolutely, then its width will no longer affect the width parent element. Therefore, specify for the list of links absolute positioning, and for category list elements - relative. Check in your browser. Then refine the position of the sublist relative to its container by setting the left and top properties (don't lower the dropdown list too low, otherwise it will disappear when you try to select a link in it).
Why was it necessary to position the category list items relatively? Remove the corresponding rule, and everything will become clear to you.
The final result should be similar to the following.
You've probably seen dynamic and animated menus on some websites that change as you scroll down. By minimizing the main navigation menu, you leave more space for content. In this tutorial, we'll explain how you can create a menu yourself using HTML5, CSS3, and a little jQuery.
If you want a special focus on the content of the site, as well as allow you to create a larger and more impressive navigation when a user first visits the website, then this type of menu is perfect for you. You can perfectly showcase your brand or logo, and after an initial look at the site, reduce some elements, allowing the user to focus on your content.
There are several ways to do this. In this tutorial, we'll explain how to create a fixed, full-width menu that resizes in height along with your logo, creating a miniaturized version of the original. If desired, you can also replace the logo with another option, such as initials or an icon, but keep in mind that consistency is very important here so that the user understands how the element has changed and what its the main objective is still the site navigation.
Creation basic structure in HTML5
We'll start by creating the basic HTML code we'll need. To start, we'll stick to a very simple HTML5 structure.
Now that our initial HTML code is written, we'll add the code for the menu, as well as some other details for the header of our HTML file.
How to create an animated menu | WebDesignMagazine
- home
- Articles
- This is a very cool site!
Scroll down and see how the menu changes
All! We've arrived!
In our : We added a meta tag for author to indicate the creator of the document, after which we included Eric Meyer's famous “CSS reset”, which will reset almost every element in the HTML file, giving you a cleaner and easier document to work with. And since we'll be using JQuery later, on the last line of our main element we'll import it via the JQuery CDN.
In our tag, we used the default HTML5 element. Ours will be full-width of the page and will be responsible for changes between large and small versions of the menu. We're giving ours a class called “large” so that we can change some specific properties in the CSS to turn our menu into a smaller version. This is our container menu that contains an image of our website logo and a simple unordered list of menus with three links.
Since we don't have any content here, this will be used to stretch the page and force scrolling to take effect.
And that's all for the HTML part. Now we need to style the elements using CSS and make the menu dynamic.
Styling menus and pages
/* Import the Amaranth font */ @import url(//fonts.googleapis.com/css?family=Amaranth); /* Main style */ body( background-color: #ebebeb; ) ul( float: right; ) li( display: inline; float: left;) img.logo(float: left;) /* Menu size and centering * / nav( width: 960px; margin: 0 auto;)
A little bit of this CSS will make our menu 960px wide in the center, while organizing our menu on the right and logo on the left. We'll also import the Amaranth font from Google Web Fonts to use for our text on the page.
Section.stretch( float: left; height: 1500px; width: 100%; ) section.stretch p( font-family: "Amaranth", sans-serif; font-size: 30px; color: #969696; text-align: center; position: relative; margin-top: 250px; ) section.stretch p.bottom( top: 100%; )
Here we are simply making the page stretch to encourage scrolling, and positioning the text to indicate the start and end of the content.
Header( background: #C7C7C7; border-bottom: 1px solid #aaaaaa; float: left; width: 100%; position: fixed; z-index: 10; ) header a( color: #969696; text-decoration: none; font-family: "Amaranth", sans-serif; text-transform: uppercase; font-size: 1em; ) header a.active, header a:hover( color: #3d3d3d; ) header li( margin-right: 30px; ) /* Dimensions for a larger menu */ header.large( height: 120px; ) header.large img( width: 489px; height: 113px; ) header.large li( margin-top: 45px; )
This is where we finish the basic styling of our header. will serve as our menu container. It will contain our element and will serve as the element where we define the background color, menu height, link menu style and more. It will adapt to the screen width with width properties: 100% and will remain fixed across other elements on the website. It's important to remember to set the z-index so that the element overlaps the rest of the page, as well as position:fixed to make the div anchored at the top so that it stays in the same position while the user scrolls through the website. As you can see, in addition to setting styles for the headers, we also set some specific styles for the “large” class using header.large. The initial state of our menu will be large, and so we're defining only the necessary styles here to make it look the way we want it when the user initially enters the page.
Dynamic menu resizing
Our menu is done and styled, but we still want to work on keeping it minimal. To create this "state", we will create a new CSS class called "small" which will be responsible for changing the properties we need to modify. We've already defined a large menu, so now we just have to make our menu shorter, our image smaller proportionally, and the (margin top) we use in our elements
/* Sizes for the smaller menu */ header.small( height: 50px; ) header.small img( width: 287px; height: 69px; margin-top: -10px; ) header.small li( margin-top: 17px; )
So as you can see, these styles are almost identical to those in the larger menu, we just changed the class “large” to “small” and changed the values we used to smaller ones. We use negative margin tops on the image to centralize it in the container since the image has a thin shadow and is taller than the writing to accommodate it. Now we have all the necessary styles to customize the resize menu, and if you try to change it in your , you will see in the browser that the menu will become smaller. But we need it to be dynamic.
Changing the menu class when jQuery help
With all our styling in place, we just need to add some JavaScript to switch between the "large" and "small" classes. Since we want to change this based on user scrolling, we will use the .ScrollTop() function in jQuery. This function will allow us to get or set the scroll position in pixels. The scroll position is the number of pixels that have already been scrolled in the browser window. In this case, we just need to know how many pixels the user scrolled so we can call our code and switch between classes:
$(document).on("scroll",function())( if($(document).scrollTop()>100)( $("header").removeClass("large").addClass("small"); ) else( $("header").removeClass("small").addClass("large"); ) ));
If the user has scrolled more than 100 pixels, then the "large" class we created will be removed and our new "small" class will be added. This way the menu will resize as we previously defined in the CSS. Give it a try, it should be working by now, but you may have noticed that the transitions between classes seem very abrupt.
CSS transitions for menu animation
In order to smoothly switch between classes in our menu, we will use CSS transitions. Just use this piece of code next to the rest of your CSS.
Header,nav, a, img, li( transition: all 1s; -moz-transition: all 1s; /* Firefox 4 */ -webkit-transition: all 1s; /* Safari and Chrome */ -o-transition: all 1s; /* Opera */ )
Here we have defined transitions for all CSS properties for. And
Liked:
26
Didn't like: 12
In this article I will show you how to write a simple jQuery plugin that will build a nice dynamic menu from regular HTML markup. The first thing we will start with is to decide what exactly the plugin will do and what our goal is. So:
Now let's determine which files need to be created to test the operation of the example in question. Here they are:
2. jquery.dynamenu.js - plugin code placed in a separate file.
3. dynamenu.css - the style of our menu. We put all the CSS here
These files with a working menu can be found in the archive attached to the article. At the end of the article there is a live demonstration of how our menu works. Please note that in the demo, the plugin call is placed in the same place as the plugin code itself. This is only due to the fact that the live demo mechanism we use requires placing the JavaScript code in a separate frame.
Let's start writing a plugin. Go!
1. Prepare HTML page markupLet's set the simplest markup for our menu. Let these be several menu items for our future website:
Site news Photoshop tutorials Photoshop brushes Beautiful fonts
Everything is simple here - 4 div elements, each with a dynamenu class, so that we can then pass it as a selector to our future plugin. Inside each div there is a hyperlink with the name of the menu item.
2. Set CSS stylesTo style our menu, we use only two CSS styles. With their help, we will make the background of each menu item gray, the menu width 300 pixels with external and internal margins of 5 pixels, and all menu links black:
a.mlink ( color:#000; text-decoration:none; ) .dynamenu ( background-color: #aaaaaa; width:300px; margin:5px; padding:5px; font-family: "Tahoma"; font-size: 9pt)
3. We write the “framework” of the pluginFirst of all, let's define the framework of our plugin. This framework is partially taken from the official jQuery website and contains the so-called “Best Practices” (best practices and techniques - from the developers of the jQuery language). In general, a similar framework applies to almost all jQuery plugins. If you remember and understand how this framework functions, then you will be able to write plugins in one go. It looks like this:
(function($) ( // list of methods of our plugin var methods = ( init: function(options) ( // plugin initialization can be placed here. in our case // for simplicity there will be nothing here ), sliding: function () ( // the sliding method of our plugin will directly build the menu ) ); // “register” our plugin in the jQuery namespace $.fn.dynamenu = function(method) ( // here we call the desired method inside the plugin ) ) (jQuery) ;
As you can see, there is nothing complicated in the frame. But it does contain useful information. The first important point to understand in the framework is that we collect all the methods added to our plugin (init, sliding) into one object - methods. This allows you to avoid clogging the $.fn namespace with unnecessary functions. Specifying the correct namespace for our plugin is a very important part of the plugin development process itself. Using a namespace ensures that our plugin is less likely to be overwritten by other plugins or code located on the same HTML page. Namespaces also make life easier because... helps you keep better track of methods, events, and data.
Always use method hiding inside the plugin, for example in a methods object. In addition to being good programming style, this technique will help you avoid conflicts with other third-party libraries and plugins, and will also help you avoid polluting the jQuery namespace
The next point worth paying attention to is the designer of our plugin. This is the line $.fn.dynamenu = function (method) (...). As you can see, the constructor takes one parameter - method. As a value for the parameter, we will pass a string containing the name of the method inside the object methods, which we are going to call. Let's populate the constructor with the following code:
$.fn.dynamenu = function(method) ( if (methods) ( methods.init.apply(this, arguments); return methods[ method].apply(this, Array.prototype.slice.call(arguments, 1)) ; ) else ( $.error("Method" + method + " does not exist!"); ) )
Let's figure out what we did. First we check if a method with the name passed in the constructor parameter exists in the object methods our plugin. If there is a method, then we first call the init method to initialize our plugin, and then we call the method whose name was passed in the constructor parameter, and we pass all the remaining arguments to it. If there is no method with the same name, then we will issue an error and the plugin will stop working.
At this stage, a lot has already been done! Now we can access our plugin and call its methods, although they do not yet perform any useful work. I recommend putting our plugin code in a separate file and calling it jquery.dynamenu.js. Placing the plugin code in a separate file is logical - after all, the plugin should be universal in its essence and allow us and other developers to connect it ready-made to their site.
Now that our framework is filled with code that can call the plugin's internal methods, it's time to build out the "meat" - that is, write the code that will directly turn our div blocks into a beautiful dynamic menu. Let's get started...
4. We write the code that creates a dynamic menu in jQueryAll useful code of our plugin will be placed in the function sliding, which is an internal method of the plugin and is located in the object methods. Let's briefly describe the sequence of steps to turn static markup with our div blocks into a dynamic menu in jQuery:
That, in fact, is the whole logic. Now let's see how to implement this:
return this.each(function() ( $(this).css(("opacity":"0.4")); $(this).hover(function() ( $("a.mlink", this).css (("font-weight":"bold")); $(this).animate(( opacity:1, "margin-left":"+=5" ), 100, "linear"); ) ( $("a.mlink", this).css(("font-weight":"normal")); $(this).animate(( opacity:0.4, "margin-left":"-=5 " ), 100, "linear"); )); ));
Just in case, I’ll explain what’s happening. So, in the very first line we see the operator. It does the following: it runs through what is passed to the function sliding set of elements (i.e. all our div blocks) and executes the code placed inside. After such a run through the elements, we return (the return statement) the result of performing the operations for each element of the set, again, in the form of a set. Thus, our sliding function returns a set of div blocks passed to the “input” of the function, only processed and already turned into a dynamic menu. This implements an important jQuery concept - the ability to use our plugin in a call chain. To better understand what a call chain is, here's an example:
$(".myelm").dynamenu("sliding").css(("border" : "1px solid red"));
In the above piece of code we see what a call chain is: first we select all the elements on the page with the myelm class, then we use our dynamenu plugin and then again along the chain we use the standard jQuery css() method to change the style of the elements. If we did not return the return this.each(function() ( ... )) construct from the method, then we would no longer be able to use the css() method in the “chain”.
Use the this.each() return operator to support chaining in your plugins and make them more versatile.
Let's move on, inside the each() operator, where we go through all our div blocks, there is just an initial setting of the element's "opacity" property to 0.4. point. The maximum opacity value is 1 (100%), so we set the "opacity" to 40%. After this, we set two handlers for “hovering” the mouse and “moving” the mouse out of the div block area. In the first handler, we set the menu item title to bold and use the animate() method to make the menu item "fully opaque" and shift it to the right by 5 pixels. In the mouse “leaving” handler, we simply return the element to its initial state - change the font again to normal and shift it to the left again by 5 pixels.
That's all! Our plugin is ready to use. Although it is simple, it can be very useful for creating a dynamic menu on the site. Below is a demonstration of how our plugin works. To see the result of the plugin, go to the Result tab.
Good luck in writing good plugins! Comments, questions and feedback are always welcome;)
Have you ever heard the statement that "you can't make a dynamic dropdown menu using just CSS in IE"? I'm sure so. So, do you actually believe this? That's right, better not believe it.
The goal we want to achieve in this article
The goal of this article is to make a dropdown menu for IE made entirely in CSS. Starting with this setting, I expanded the task to make such a menu work in other most famous browsers (from the comments it turns out that these browsers are Opera 7.x and the latest versions of Firefox).
The goal that we want to achieve in this article is, in principle, more or less general educational, i.e. give a general idea of some of the "hidden" and rarely used features of browsers.
Also, those who are especially curious can find in this article some tricks with which you can achieve certain non-standard results. Well, for developers, this article can become a reason for thought or a source of new ideas.
How do we imagine the level of the reader?
I was actually thinking about labeling this article as "advanced". But I am sure that even not the most experienced developers will understand well what is written in the article. In short, the reader simply must know the basics of CSS and
HTML.
How is this menu different from all others?
I spent a long time looking online for menus that were made in CSS, but I didn’t find a single solution that would work without glitches in IE. However, I found many interesting ideas that led me to the result that will be described here. Yes, my code isn't perfect either, but I simply don't have the time to fix all the errors. The most interesting alternative solution I've seen (that uses CSS) is based on using the hover pseudo-class for LI elements. But I never thought that this was possible, just as I never thought that it was even possible to make a drop-down menu for IE without scripts...
The main difference between mine and other menus is that mine runs in IE. All the solutions I've seen use the LI element as the main element for the :hover pseudo-class, however Microsoft has decided that this pseudo-class can only be used for
element A. Most sites make a reservation that their menus only work in Opera 7.x or Mozilla browsers. But these browsers are used by only five percent of users! Yes, such menus are good in these browsers, but unfortunately they cannot be visible in most of the most common browsers. Now we will correct this misunderstanding.
What is a menu made with just CSS?
This is a dynamic menu that is created using only CSS and no scripts (for example, written in JavaScript).
What, you can’t believe it?
Let's look at the code:
<
STYLE type
=
text
/
css id
=
"default"
title
=
"default"
name
=
"default"
>
*::- moz - any - link br ,*:- moz - any - link br (
/*a workarround for mozilla*/
display: none;
}
div #menu * (
cursor: pointer; /*because IE displays the text cursor
if the link is inactive*/
}
Disabled (
color : red ! important ;
background: none! important ;
}
Div #menu (
background : #F5F5DC;
height: 15px;
white - space : nowrap ;
width: 100%;
}
Div #menu .a (
background : #F5F5DC;
border : 1px solid #F5F5DC;
color : #000000;
text - decoration : none ;
}
Div #menu .a table (
display: block;
font: 10px Verdana, sans-serif;
white - space : nowrap ;
}
Div #menu table, div#menu table a (
display: none;
}
Div #menu .a:hover, div#menu div.menuitem:hover (
background : #7DA6EE;
border : 1px solid #000080;
color : #0000FF;
margin - right :- 1px ; /*resolves a problem with Opera
not displaying the right border*/
}
Div #menu .a:hover table, div#menu div.menuitem:hover table(
background : #FFFFFF;
border : 1px solid #708090;
display: block;
position: absolute;
white - space : nowrap ;
}
Div #menu .a:hover table a, div#menu div.menuitem:hover table a (
border - left : 10px solid #708090;
border - right : 1px solid white ; /*resolves a jump problem*/
color : #000000;
display: block;
padding: 1px 12px;
text - decoration : none ;
white - space : nowrap ;
z-index: 1000;
}
Div #menu .a:hover table a:hover, div#menu div.menuitem:hover table a:hover (
background : #7DA6EE;
border : 1px solid #000000;
border - left : 10px solid #000000;
color : #000000;
display: block;
padding: 0px 12px;
text - decoration : none ;
z-index: 1000;
}
Td(
border - width : 0px ;
padding: 0px 0px 0px 0px;
}
menuitem (
float: left;
margin : 1px 1px 1px 1px ;
padding: 1px 1px 1px 1px;
}
Menuitem*(
padding: 0px 0px 0px 0px;
}
#other (
}
#moz(
}
#moz::-moz-cell-content(
height: auto; visibility: visible;
}
#other::-moz-cell-content(
height: 1px; visibility: hidden;
}
#holder (
width: 100%;
}
<
TABLE id
=
holder
>
<
TR
>
<
TD id
=
"other"
>
<
DIV id
=
"menu"
>
<
DIV
class=
"menuitem"
>
<
a
class=
"a"
href
=
"#"
>File<
BR
>
<
TABLE
>
<
TR
>
<
TD
><
a href
=
#2>click me
<
TR
>
<
TD
><
a href
=
#3>Save
<
TR
>
<
TD
><
a href
=
#4>Close
<
DIV
class=
"menuitem"
>
<
A
class=
"a"
href
=
"#11"
>Help<
BR
>
<
TABLE
>
<
TR
>
<
TD
><
a
class=
"disabled"
>..
<
TR
>
<
TD
><
a href
=
#13>Index
<
TR
>
<
TD
><
a href
=
"#14"
>About
<
TR
>
<
TD id
=
"moz"
>Mozilla specific menu!
<
DIV id
=
"menu"
>
<
DIV
class=
"menuitem"
>
<
a
class=
"a"
href
=
"#"
>Filezilla
<
TABLE
>
<
TR
>
<
TD
><
a href
=
#2>Open
<
TR
>
<
TD
><
a href
=
#3>Save
<
TR
>
<
TD
><
a href
=
#4>Close
<
DIV
class=
"menuitem"
>
<
A
class=
"a"
href
=
"#11"
>Helpzilla
<
TABLE
>
<
TR
>
<
TD
><
a
class=
"disabled"
>..
<
TR
>
<
TD
><
a href
=
#13>Index
<
TR
>
<
TD
><
a href
=
"#14"
>About
<
BR
>
What's going on, why is everything working?
Let me make a reservation right away that in this article I will not teach you how to use CSS. Therefore, we immediately move on to consider the principle of operation of the menu - to the pseudo-class ":hover". Yes, this is exactly the class. Those. a selector can inherit another selector that includes ":hover". In our case, "A:hover TABLE" selects "