During hover on parent element, show child (dropdown nav) - javascript

I'm trying to make a stupid horizontal nav bar with a drop-down on some of the items. The way I decided to do it is just by putting the drop-down in a div tag. This is easily changeable, i just don't like to go heavy on the html side.
Basically I just want my drop down to work when you hover over the parent element. Additional css is going to be used to make it pretty and positioned better.
Here's my js:
var dropdown = $('.dropdown');
var parent = dropdown.parent();
$(parent).hover(
function () {
dropdown.css('display', 'block');
}
);
Here's my css:
div.nav {
text-align: center;
}
div.nav > ul > li {
margin-top: 15px;
text-align: center;
font-size: 1.25em;
}
div.nav > ul > li {
display: inline-block;
list-style-type: none;
}
div.nav a {
padding: 1em;
}
div.dropdown {
display: none;
background-color: black;
position: absolute;
}
Here's my html:
<div class="nav">
<ul>
<li>Home</li>
<li>
Sample Game
<div class="dropdown">
About it
<br>
Game
</div>
</li>
<li>TP Solutions</li>
<li>Projects</li>
<li>Contact Me</li>
</ul>
<div class="clear"></div>

You should not be using "parent" as a variable name, as it's a reserved word.
$(document).ready(function() {
var $dropdown = $('.dropdown'),
$parent = $dropdown.parent();
$parent.on("mouseover",
function () {
$dropdown.css('display', 'block');
}
);
$parent.on("mouseout",
function () {
$dropdown.css('display', 'none');
}
);
});

According to the oreder this has to be done:
add a jQuery plugin first
Then add your script
so the order will be like this:
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js'>
</script>
<script>
$(function(){
var dropdown = $('.dropdown');
var parent = dropdown.parent();
$(parent).hover(function () {
dropdown.css('display', 'block');
});
});
</script>

Please try the below code.
$(".nav").on("mouseenter","li",function(){
$(this).find(".dropdown").show();
});
$(".nav").on("mouseleave","li",function(){
$(this).find(".dropdown").hide();
});
In your code " dropdown.parent(); " -> this will refer all the parents which have child dropdown and will show the menu. we need to refer current hover parent. Please check the working example in below link.
http://jsfiddle.net/renjith/wX48f/

There are so many good solutions to use jQuery and CSS to show a drop down menus. So you don't need to reinvent the wheel. Here are some examples that you might be able to find one to fit your need.

Related

how to shorten the breadcrumb when it appears in mobile website

when i view my website in mobile with lot of filters, the breadcrumb length becomes too large. so i want to replace all the li tags that are behind the second last li. that means all the li except first, last and last-1 li need to be replaced with dots.
Anybody can help me fix this with jquery, javascript, or css?
<ul class="left">
<li class="active">Airways</li>
<li>Trauma</li>
<li>Medical</li>
<li>OB | Peds</li>
<li>Patient Assessment</li>
<li>Proprietary</li>
<li>Trauma</li>
<li>Medical</li>
<li>OB | Peds</li>
<li>Patient Assessment</li>
<li>Proprietary</li>
</ul>
This is just example code i have added here.
You can try with jquery like this. Basically if it is a smaller width device, and if it is not first, last or second last child, the text of the link tag is replaced by '..' .
<script>
$(document).ready(function () {
if (window.matchMedia("(max-width: 767px)").matches)
{
// The viewport is less than 768 pixels wide
console.log("This is a mobile device.");
$('ul.left li').each(function() {
$this = $(this); // cache $(this)
if (! $this.is(':first-child') && ! $this.is(':nth-last-child(2)') && ! $this.is(':last-child') ) {
$this.find('a').text("..");
}
});
}
});
</script>
This is my first answer on stack overflow, hope this is what you want this is the codepen link
https:// codepen.io/vatzkk/pen/yLYMJeG
HTML
<script src="https://kit.fontawesome.com/a076d05399.js"></script>
<ul class="left" id="bread">
<li class="active">Airways</li>
<li id="dropdown" style="display:none">
<div class="dropdown" >
<i class="dropbtn">...</i><i class="fas fa-caret-down"></i>
<div class="dropdown-content" id="dropdown-list">
</div>
</div>
</li>
<li>Trauma</li>
<li>Medical</li>
<li>OB | Peds</li>
<li>Patient Assessment</li>
<li>Proprietary</li>
<li>Trauma</li>
<li>Medical</li>
<li>OB | Peds</li>
<li>Patient Assessment</li>
<li>Proprietary</li>
</ul>
Javascript
//you can add your conditions over here
document.getElementById("dropdown").style.display="block";
var arr=[...document.getElementById("bread").children];
var dropdownItems=arr.slice(2,-2);
dropdownItems.map(item=>{
document.getElementById("bread").removeChild(item);
document.getElementById("dropdown-list").appendChild(item);
});
Pure CSS Working example: https://jsfiddle.net/3o8vuwd6/2/
First give your list a class
<ul class="left breadcrumblist">
CSS:
/* This is just to give it some styling as you haven't given any */
.breadcrumblist li {
list-style: none;
display: inline-block;
padding-right: 0.5em;
}
.breadcrumblist li + li::before{
content: "/";
padding-right: 0.5em;
}
/* adjust to your breakpoint. 9999 just so it works on large screen as an example */
#media only screen and (max-width: 9999px) {
/* hide all */
.breadcrumblist li{
display: none;
}
/* show first and last */
.breadcrumblist li:first-child,
.breadcrumblist li:last-child{
display: inline-block;
}
/* add ... to the end of the first one */
.breadcrumblist li:first-child::after{
content: "...";
padding-left: 0.5em;
}
/* fiddle with the content we added in styling */
.breadcrumblist li + li::before{
content: "";
padding-right: 0;
}
}
Thank you all for your guidance and finally i made something work according to my requirement and also i want to share it here because in case in future if someone looks for the same issue he or she can be benefited from this. This is also from the modifications that all you have just posted above.
<ul class="left" id="bread_cumb">
$(document).ready(function(){
if (window.matchMedia("(max-width: 767px)").matches)
var width = $(window).width();
if (width < 720) {
$('#bread_cumb li:not(:first-child):not(:nth-child(2)):not(:last-
child):not(:nth-last-child(2))').html('<span style="margin-
left:7px;margin-right:7px;"> ... </span>');
var last =$('#bread_cumb li:last-child').text();
var re = /^([A-Za-z0-9_'",.!##$%^&*()-+=?/\|:]+)[\s,;:]+([a-z]+)/i;
var m = re.exec(last);
$('#bread_cumb li:last-child').html('<a>'+m[1]+' '+m[2]+'...</a>');
}
});
Thanks all for your valuable ideas.

Add & remove classes with fewer lines of code

I'm trying to learn how to shorten my jQuery code. Any suggestions or tips would be awesome:
jQuery(document).ready(function($){
$('#checkout_timeline #timeline-4').click(function() {
if ($('#checkout_timeline #timeline-4').hasClass('active')) {
$('#checkout-payment-container').addClass('cpc-visible');
}
});
$('#checkout_timeline #timeline-1, #checkout_timeline #timeline-2, #checkout_timeline #timeline-3').click(function() {
$('#checkout-payment-container').removeClass('cpc-visible');
});
});
To avoid clutter, please find the working version here:
My JSFiddle Code
I know I can use .show() and .hide() but due to other CSS considerations I want to apply .cpc-visible.
There are a handful of things you can improve here. First, you're over-specifying. Ids are unique. No need to select #checkout_timeline #timeline-4 when just #timeline-4 will do. But why even have ids for each li? You can reference them by number using the :nth-child(n) selector. Or better yet, you've already given them application-specific class names like billing, shipment, and payment. Use those! Let's simplify the original content to:
<ul id="checkout_timeline">
<li class='billing'>Billing</li>
<li class='shipping'>Shipping</li>
<li class='confirm'>Confirm</li>
<li class='payment active'>Payment</li>
</ul>
<div id='checkout-payment-container' class='cpc-visible'>
This is the container to show and hide.
</div>
Notice I left the active class, and indeed further initialized the checkout
div with cpc-visible to mirror the payment-is-active condition. Usually I would keep HTML as simple as possible and put "starting positions" initialization in code. But "in for a penny, in for a pound." If we start with payment active, might as well see that decision through, and start the dependent div in a consistent state.
Now, revised JavaScript:
jQuery(document).ready(function($) {
$('#checkout_timeline li').click(function() {
// make clicked pane active, and the others not
$('#checkout_timeline li').removeClass('active');
$(this).addClass('active');
// show payment container only if payment pane active
var paymentActive = $(this).hasClass('payment');
$('#checkout-payment-container').toggleClass('cpc-visible', paymentActive);
});
});
This code is much less item-specific. It doesn't try to add separate click handlers for different tabs/panes. They all get the same handler, which makes a uniform set of decisions. First, that whichever pane is clicked, make it active and the others not active. It does this by removing all active classes, then putting active on just the currently selected pane. Second, it asks "is the current pane the payment pane?" And it uses the toggleClass API to set the cpc-visible class accordingly. Often such "set class based on a boolean condition" logic is simpler and more reliable than trying to pair appropriate addClass and removeClass calls.
And we're done. Here's a JSFiddle that shows this in action.
Try this : You can user jquery selector with timeline and active class to bind click event handler where you can add required class. Same selector but not having active class to remove class.
This will be useful when you add / remove elements and will be more flexible.
jQuery(document).ready(function($){
$('#checkout_timeline .timeline.active').click(function() {
$('#checkout-payment-container').addClass('cpc-visible');
});
$('#checkout_timeline .timeline:not(.active)').click(function() {
$('#checkout-payment-container').removeClass('cpc-visible');
});
});
JSFIddle
Here is one of the ways, you can shorten this code by using :not(). Also its better to use elements than to reference and get them via JQuery always.
jQuery(document).ready(function($) {
var showHideContainer = $('#checkout-payment-container');
$('#checkout_timeline .timeline.active').click(function() {
showHideContainer.addClass('cpc-visible');
});
$('#checkout_timeline .timeline:not(.payment)').click(function() {
showHideContainer.removeClass('cpc-visible');
});
});
try this code its working fine with fiddle
$('.timeline').click(function() {
if ($(this).hasClass('active') && $(this).attr("id") == "timeline-4")
$('#checkout-payment-container').addClass('cpc-visible');
else
$('#checkout-payment-container').removeClass('cpc-visible');
});
This would of been my approach cause you still have to add/remove the active class between each li.
jQuery(document).ready(function($) {
$('ul li').click(function() {
$('ul li.active').removeClass('active');
$(this).closest('li').addClass('active');
k();
});
var k = (function() {
return $('#timeline-4').hasClass('active') ? $('#checkout-payment-container').addClass('cpc-visible') : $('#checkout-payment-container').removeClass('cpc-visible');
});
});
#checkout-payment-container {
float: left;
display: none;
background: red;
color: white;
height: 300px;
width: 305px;
padding: 5px;
}
ul {
list-style: none;
width: 100%;
padding: 0 0 20px 0px;
}
li {
float: left;
padding: 5px 11px;
margin-right: 5px;
background: gray;
color: white;
cursor: pointer;
}
li.active {
background: black;
}
.cpc-visible {
display: block !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="checkout_timeline">
<li id='timeline-1' class='timeline billing'>Billing</li>
<li id='timeline-2' class='timeline shipping'>Shipping</li>
<li id='timeline-3' class='timeline confirm'>Confirm</li>
<li id='timeline-4' class='timeline payment'>Payment</li>
</ul>
<div id='checkout-payment-container'>
This is the container to show and hide.
</div>
Your code look great, i would have written it the same.
bit sure how much it helps but if you like, you can use inline if like this:
$(document).ready(function(){
$('#B').click(function() { (!$('#B').hasClass('active')) ?
$('#A').addClass('active') : ''; });
$('#C').click(function() { $('#A').removeClass('active'); });
});
Link for a live example:
jsFiddle

addClass and removeClass is not working correctly

Sorry if this is an extremely simple question, but for some reason, I cant get this working.
What I'm trying to do is to add the activeButton class to each list item you click and remove the activeButton class to the list-item that had the activeButton class before the list-item was clicked.
Here is a code snippet of my problem
$(document).ready(function () {
$('.buttons').click(function () {
$('.activeButton').removeClass('.activeButton');
$(this).addClass('.activeButton');
});
});
.buttons {
/*This is for decorative and visual purposes.
So you can ignore the CSS for now.*/
display: inline-block;
margin: 10px;
}
.activeButton {
border-bottom: 1px solid black;/*I use border-bottom to provide underlines for my text. This allows the underline to be transitioned or animated*/
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class="buttons activeButton">Link1</li>
<li class="buttons">Link2</li>
<li class="buttons">Link3</li>
<li class="buttons">Link4</li>
</ul>
For the sake of clarification, I will explain my goal and the current problem.
GOAL: Once a list item is clicked, the class .activeButton will be added to the list item that was clicked and the JS will remove .activeButton from the list item that originally had the activeButton class.
PROBLEM: The attempted solution that I have coded does not work.
Like this you mean?
$(document).ready(function () {
$('.buttons').click(function () {
$('.buttons').removeClass('activeButton'); // <-- remove from all .buttons class
$(this).addClass('activeButton'); // <-- add to clicked link only
});
});
.buttons {
/*This is for decorative and visual purposes.
So you can ignore the CSS for now.*/
display: inline-block;
margin: 10px;
}
.activeButton {
border-bottom: 1px solid black;/*I use border-bottom to provide underlines for my text. This allows the underline to be transitioned or animated*/
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class="buttons activeButton">Link1</li>
<li class="buttons">Link2</li>
<li class="buttons">Link3</li>
<li class="buttons">Link4</li>
</ul>
You don't need the class selector in the strings you pass to addClass() and removeClass().
Update as follows:
$(function () {
$('.postalProvider').click(function () {
$('.activeButton').removeClass('activeButton');
$(this).addClass('activeButton');
});
});
Update :
$(document).ready(function () {
var $buttons = $('.buttons');
$buttons.click(function () {
$buttons.removeClass('.activeButton');
$(this).addClass('.activeButton');
});
});
I think this is what you were after.

Adding a class to a link inside a <li> element on scrolling

Is it possible to add a class to a link inside a li element when a certain part of the page is active?
I have a one page website and would like to change the color of the link when that specific part of the page is reached via scroll.
Here's my HTML:
<header id="header">
<section class="container">
<nav>
<a class="logo" href="index.html">Logo</a>
<div id="menu">
<ul id="links">
<li>Services</li>
<li>About</li>
<li>Clients</li>
<li class="last">Contact</li>
</ul>
</div>
</nav>
</section>
</header>
And here's the CSS:
#menu li a {
color:#7a7a7a;
text-decoration: none;
font-size: 12px;
margin-right:20px;
}
#menu li.last a {
color:#7a7a7a;
text-decoration: none;
font-size: 12px;
margin-right:0px;
}
#menu li.current a {
color: #0086be;
}
What I would like to do is to add the class .current to the link inside the li element whenever that specific part of the page is reached.
I believe this is only possible with Javascript, can anyone point me the right path to achieve this?
Thanks in advance
I think you want something like scrollspy in bootstrap,
you can use it or you can find https://gist.github.com/pascaldevink/2380129 bypascaldevink
or here is the fiddle http://jsfiddle.net/ia_archiver/Kb7xq/
You will require jquery for this,
$.fn.scrollspy = function ( option ) {
return this.each(function () {
var $this = $(this)
, data = $this.data('scrollspy')
, options = typeof option == 'object' && option
if (!data) $this.data('scrollspy', (data = new ScrollSpy(this, options)))
if (typeof option == 'string') data[option]()
})
}
$.fn.scrollspy.Constructor = ScrollSpy
$.fn.scrollspy.defaults = {
offset: 10
}
$(function () {
$('[data-spy="scroll"]').each(function () {
var $spy = $(this)
$spy.scrollspy($spy.data())
})
})
}(window.jQuery);
Using hover function you can achieve this.i.e. on hover of specific part of the page you add the class to the link present inside the li. e.g.
$('#specificPartOfPageId').hover(function(){
$('#links').children().children('a').addClass('current');
});
This would add .current class to every link present inside that UL element.
Hope this helps.
If I have understood correctly, I guess this is what you require: jsFiddle. The CSS and the HTML code remains the same and this is the jQuery code which I've used:
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll > 500) {
$("#links li:first-child").addClass("current");
}
if (scroll > 750) {
$("#links li:first-child").removeClass("current");
$("#links li:nth-child(2)").addClass("current");
}
var scrollBottom = $(window).scrollTop() + $(window).height();
if (scroll < 500) {
$("#links li:first-child").removeClass("current");
}
if (scroll < 750) {
$("#links li:nth-child(2)").removeClass("current");
}
});
Basically what happens is that when you scroll down to 500px, the li:first-child is automatically assigned the current class. You can modify the jQuery to suit your needs by adding more if queries as per your needs. You can target different <li>'s in your list using different child-selectors like li:first-child, li:nth-child(2) etc.

Issue Unhiding div Using Javascript

Have successfully setup a menu which cycles between multiple tabs using Javascript. The issue is I'm using SiteLevel as a search for this site. I want the search box to be a part of the hide/unhide menu but the script (I've also tried the html code for the search box, but still no fix)
I've paired it down to the simplest form of this concept to ensure that it's not some other css or script that's conflicting, but it still opens to a blank box here's the code.
I've pumped it into http://jsfiddle.net/Split98/A3DVa/
Software
Hardware
Supplies
Contact
Search
<div id="nav">
<div id="software">Hello!</div>
<div id="hardware">Yes!</div>
<div id="supplies">Yeee Haw!</div>
<div id="contact">Bingo!</div>
<div id="search"><script type="text/javascript" src="http://www.sitelevel.com/javabox?crid=ze32uipb"></script></div>
</div>
CSS:
#nav div {
display: none;
background-color: red;
height: 200px;
}
jQuery:
$(function(){
var divs = $('#nav div'),
links = $('a');
links.click(function () {
$(this.hash).toggle().siblings().hide();
return false;
});
})
Thanks in advance guys!
LIVE DEMO
Simply use #nav > div in your CSS
Will target only the immediate childrens.Otherwise all DIV elements will be hidden (your search tool)
#nav > div {
display: none;
background-color: red;
height: 200px;
}
edited jQuery
$(function () {
var divs = $('#nav div'),
links = $('a');
divs.eq(0).show(); // if you need it.....
links.click(function ( e ) { // e = event
e.preventDefault(); // instead of return false;
$(this.hash).toggle().siblings().hide();
});
});

Categories

Resources