Open and close Bootstrap dropdown by clicking a single element only - javascript

I have a simple Bootstrap 3 dropdown menu that I want to keep open at all times except when clicking on the element(anchor) that opened it. So the same element should be responsible for showing and hiding the dropdown. I want to be able to click everywhere in the UI except the element that opens and closes the dropdown.
I have tried many different approaches to solve this with e.stopPropagation();. I have tried it with jQuery .off() function..
I successfully managed to solve the problem of keeping the dropdown open when clicking inside the dropdown menu with the following code, but whenever clicking outside it closes the menu:
<ul class="nav navbar-nav navbar-right">
<li class="dropdown">
<i class="fa fa-sort-alpha-asc"></i>
<!-- Dropdown Menu -->
<ul class="dropdown-menu" role="menu">
<li>
// Menu content
</li>
</ul>
</li>
</ul>
<script>
$(document).on('click', '.dropdown .dropdown-menu', function (e) {
e.stopPropagation();
});
</script>

A solution could be to bind to click events on the body, and check if you pressed the link for the dropdown.
If you click the link for the dropdown, save that in a variable (pressedLink).
When the event runs for hiding the dropdown, return the pressedLink variable. If you return false from the event, nothing more will happen, and the dropdown stays open.
var pressedLink = false;
$("body").on("click", function(e) {
if (e.target.id === "only-toggle-when-pressing-me") {
pressedLink = true;
} else {
pressedLink = false;
}
});
$('.dropdown').on('hide.bs.dropdown', function () {
return pressedLink;
})
#wrapper {
background-color: red;
padding: 20px;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
.nav {
background-color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<div id="wrapper">
<ul class="nav navbar-nav navbar-right">
<li class="dropdown">
<i id="only-toggle-when-pressing-me" class="fa fa-sort-alpha-asc">link</i>
<!-- Dropdown Menu -->
<ul class="dropdown-menu" role="menu">
<li>
// Menu content
</li>
</ul>
</li>
</ul>
</div>

Related

Hovering Bootstrap Navbar gap issue

I want to have a hovering navbar, which works fine, but I want to keep in with the style of the site. The site's dropdown is 20px below the navbar, when you hover the navbar and go to travel to the dropdown it hides. It looks similar to this:
Heres and example on codepen.io
.dropdown:hover>.dropdown-menu {
display: block;
}
.dropdown>.dropdown-toggle:active {
/*Without this, clicking will make it sticky*/
pointer-events: none;
}
.dropdown-menu{
margin-top:20px;
}
You can try the following solution using an inner <div> element to push the menu items down. I also recommend to use a additional class for your customization (in this case .custom-dropdown) so you only change the custom dropdown and not all dropdown elements on your side.
html, body {
background: #ccc;
}
.custom-dropdown.dropdown:hover > .dropdown-menu {
display: block;
margin: 0;
background: transparent;
}
.custom-dropdown.dropdown > .dropdown-toggle:active {
/** without this, clicking will make it sticky. */
pointer-events: none;
}
.custom-dropdown .dropdown-menu .inner-dropdown-menu {
margin-top: 20px;
padding: .5rem 0;
background: white;
}
<html>
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
<div class="dropdown custom-dropdown">
<button class="btn btn-primary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dropdown button</button>
<div class="dropdown-menu border-0" aria-labelledby="dropdownMenuButton">
<div class="inner-dropdown-menu border rounded">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<a class="dropdown-item" href="#">Something else here</a>
</div>
</div>
</div>
</div>
</body>
</html>
How about you remove the margin-top property and make it into padding-top:20px;. That would eliminate the gap and make the dropdown bar more spacious. I do not know if that is what you wanted, I could not understand your question accurately
It is not possible only with CSS. You have to write little java-script also.
You can write on focus event and change the css of dropdown menu. Then write click event out of menu element then hide. This way we can solve this issue. If you really want space between menu link and dropdown avoid using hover make it click.

How to apply animations to items in a list

I am new to HTML, CSS and JS/jQuery. I'm creating a test website just to get familiar with jQuery and can't seem to figure an issue out.
I have a navigation bar at the top of the page which contains a logo on the left and links on the right. I've set up the below jQuery code to fade the links in and out upon mouse enter/leave:
$(document).ready(main);
function main() {
$('.marquee').marquee({
/* pauseOnHover: true */
})
$('.nameorlogo, .navitems').mouseenter(function() {
$('.nameorlogo').fadeTo('fast', 1);
$('.navitems').fadeTo('fast', 1);
})
$('.nameorlogo, .navitems').mouseleave(function() {
$('.nameorlogo').fadeTo('fast', 0.5);
$('.navitems').fadeTo('fast', 0.5);
})
};
Here is the html:
<!DOCTYPE html>
<html>
<head>
<title>JSTest1</title>
<link href="../css/style.css" type="text/css" rel="stylesheet">
<script type="text/javascript" src='../js/jquery-3.2.0.js'></script>
<script type="text/javascript" src='../js/main.js'></script>
<script type="text/javascript" src='../js/marquee.js'></script>
</head>
<body>
<header class=topheader>
<nav class=navtop>
<div class=nameorlogo>
<h1>JSTest1</h1>
</div>
<div>
<ul class=navitems>
<li>Contact</li>
<li>Services</li>
<li>About</li>
<li>Home</li>
</ul>
</div>
</nav>
</header>
<main>
<div class=marquee>This is a test for JavaScript</div>
</main>
</body>
</html>
The problem I have is when I hover over a link, either nav links or the logo, everything fades in and out, I want them all to be independant.
I know you can do this in CSS, this is purely to help me learn and understand.
Thanks for your help.
Jim
Use the the this keyword like $(this) to refer to the currently hovered item
$(this).fadeTo('fast', 1);
Also, notice that .navitems is the whole UL element, while you need to target the LI elements. Therefore
$('.nameorlogo, .navitems li').mouseenter(function()
Additionally here's other similar ways to achieve what you desire:
using .on() method
$('.nameorlogo, .navitems li').on({
mouseenter : function() {
$(this).stop().fadeTo(250, 1);
},
mouseleave : function() {
$(this).stop().fadeTo(250, 0.5);
},
});
// .stop() is here to prevent animation buildups
.nameorlogo,
.navitems li{
opacity: 0.5;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class=nameorlogo>
<h1>JSTest1</h1>
</div>
<div>
<ul class=navitems>
<li>Contact</li>
<li>Services</li>
<li>About</li>
<li>Home</li>
</ul>
</div>
Using .hover() method
$('.nameorlogo, .navitems li').hover(function(evt) {
var isMouEnt = evt.type === "mouseenter";
$(this).stop().fadeTo(250, isMouEnt ? 1 : 0.5);
});
// .stop() is here to prevent animation buildups
.nameorlogo,
.navitems li{
opacity: 0.5;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class=nameorlogo>
<h1>JSTest1</h1>
</div>
<div>
<ul class=navitems>
<li>Contact</li>
<li>Services</li>
<li>About</li>
<li>Home</li>
</ul>
</div>

Tab panels swipe-able in mobile view?

I have a tabbed menu and I want the tabbed menu (the ul class="tabs") to be swipe-able in mobile view.
EDIT: I found a snippet on using Slick JS, I never knew about this JS but I want it to apply this codepen on my current tabbed menu.
How to combine with my current tabbed menu properly? I tried to combine it but the current UI design of my tabbed menu getting messed up.
Here's my codepen of tabbed menu
<section class="wrapper">
<ul class="tabs">
<li class="active"><span class="icons-tabbed icon-icon-tab-locator">Tab 1</span></li>
<li><span id="partner-store" class="icons-tabbed icon-icon-tab-howto">Tab 2</span></li>
<li><span id="partner-store" class="icons-tabbed icon-icon-tab-howto">Tab 3</span></li>
</ul>
<ul class="tab__content">
<li class="active">
<div id="tab1" class="content__wrapper">
</div>
</li>
If all you want to do is swipe horizontally on a menu, to reveal any other nav items not visible in the viewport, you can do that with css.
#media screen and (max-width: 768px) {
.tabs {
overflow-x: scroll;
white-space: nowrap;
}
}
Use jquery.mobile. This is ideal for your purpose. I wrote a sample of how it works. What you will have to do next is to bind the swipe event with your click tabs. I suggest you use next() for the right swipe and prev() for left swipe to target the tabs.
See this sample:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<script>
$(document).on("pagecreate","#pageone",function(){
$("p").on("swipeleft",function(){
alert('swiped left');
});
$("p").on("swiperight",function(){
alert('swiped right');
});
});
</script>
</head>
<body>
<div data-role="page" id="pageone">
<div data-role="header">
</div>
<div data-role="main" class="ui-content">
<p style="background:red; height:250px; font-size:50px">If you swipe me in the left or right, an event will be triggered.</p>
</div>
</div>
</body>
</html>

Bootstrap scrollspy not working and nav menu buttons are causing the header to reload

Basically all anchor hrefs work except that the scrollspy is not working. Data-offset is not working also.On click only the first li 'Home' is changing its background all others are not working. When scrolling down to #search-nav #obqvi #about and so on menu buttons related to them are not getting colored also so this means my scrollspy is not working at all.
Also when i click one of the anchors the whole header menu buttons reload it happens for around 0.1s but its ugly.
http://getbootstrap.com/javascript/#scrollspy this is the link im using as template and i cannot see any difference compared to my code
HTML :
<body data-spy="scroll" data-target=".navbar" data-offset="0">
<header>
<nav class="navbar navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#"><img id="logo-img" src="images/logo.png" alt="logo"></a>
</div>
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav">
<li>Home</li>
<li><span class="glyphicon glyphicon-search"></span> Search</li>
<li><span class="glyphicon glyphicon-home"></span> Sales</li>
<li><span class="fa fa-cogs"></span> Services</li>
<li><span class="glyphicon glyphicon-comment"></span> Contact</li>
<li><span class="glyphicon glyphicon-link"></span> About Us</li>
</ul>
</div>
</div>
</nav>
</header>
....
Edited with Jquery script but it still does not work when i click on 'a' i get smooth scrolling to the position thats alright
but when i scroll with the scrollwheel the button related to the section doesnt get colored and on click also it doesnt get colored
JS:
<script>
$(document).ready(function(){
$('.btn-information').click(function(){
$('#myModal').modal('show');
});
// Add scrollspy to <body>
$('body').scrollspy({ target: ".navbar", offset: 50 });
// Add smooth scrolling on all links inside the navbar
$("#myNavbar a").on('click', function (event) {
// Prevent default anchor click behavior
event.preventDefault();
// Store hash
var hash = this.hash;
// Using jQuery's animate() method to add smooth page scroll
// The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function () {
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
});
});
</script>
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<style>
body {
position: relative;
}
#search-nav {
padding-top: 50px;
height: 500px;
color: #fff;
background-color: #1E88E5;
}
#obqvi {
padding-top: 50px;
height: 500px;
color: #fff;
background-color: #673ab7;
}
#about {
padding-top: 50px;
height: 500px;
color: #fff;
background-color: #ff9800;
}
#footer-contact-form {
padding-top: 50px;
height: 500px;
color: #fff;
background-color: #ff9800;
}
#end-footer {
padding-top: 50px;
height: 500px;
color: #fff;
background-color: #ff9800;
}
</style>
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">WebSiteName</a>
</div>
<div>
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav">
<li>Home</li>
<li><span class="glyphicon glyphicon-search"></span> Search</li>
<li><span class="glyphicon glyphicon-home"></span> Sales</li>
<li><span class="fa fa-cogs"></span> Services</li>
<li><span class="glyphicon glyphicon-comment"></span> Contact</li>
<li><span class="glyphicon glyphicon-link"></span> About Us</li>
</ul>
</div>
</div>
</div>
</nav>
<div id="search-nav" class="container-fluid">
<h1>Section 1</h1>
<p>Click on the different Section links in the navbar to see the smooth scrolling effect.</p>
</div>
<div id="obqvi" class="container-fluid">
<h1>Section 2</h1>
<p>Click on the different Section links in the navbar to see the smooth scrolling effect.</p>
</div>
<div id="about" class="container-fluid">
<h1>Section 3</h1>
<p>Click on the different Section links in the navbar to see the smooth scrolling effect.</p>
</div>
<div id="footer-contact-form" class="container-fluid">
<h1>Section 3</h1>
<p>Click on the different Section links in the navbar to see the smooth scrolling effect.</p>
</div>
<div id="end-footer" class="container-fluid">
<h1>Section 3</h1>
<p>Click on the different Section links in the navbar to see the smooth scrolling effect.</p>
</div>
<script>
$(document).ready(function () {
// Add scrollspy to <body>
$('body').scrollspy({ target: ".navbar", offset: 50 });
// Add smooth scrolling on all links inside the navbar
$("#myNavbar a").on('click', function (event) {
// Prevent default anchor click behavior
event.preventDefault();
// Store hash
var hash = this.hash;
// Using jQuery's animate() method to add smooth page scroll
// The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function () {
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
});
});
</script>
</body>
</html>
I don't know if it will help, but I had to include the following in my js when I was using a scroll spy function. Also - check that you have the required files for the scroll spy to work and that jquery is loaded and called into the page first.
// jQuery for page scrolling feature - requires jQuery Easing plugin
$(function() {
$('a.page-scroll').bind('click', function(event) {
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top
}, 1500, 'easeInOutExpo');
event.preventDefault();
});
});
// Highlight the top nav as scrolling occurs
$('body').scrollspy({
target: '.navbar-fixed-top'
})

Highlight the navigation tab on current page with CSS?

I'm new to html/css stuff so please bear with me.
I have specific images that I want to use as a navigation menu.
My html,css basically look something like this:
HTML
<div id="navigation">
<a id="main" href="domain.com/main">main</a>
<a id="tips" href="domain.com/tips">tips</a>
<a id="news" href="domain.com/news">news</a>
</div>
CSS
a#main:
{
background-image:url(main-normal.png);
margin-right:0px;
}
a#main:hover:
{
background-image:url(main-highlight.png);
}
a#tips:
{
background-image:url(tips-normal.png);
margin-right:0px;
}
a#tips:hover:
{
background-image:url(tips-highlight.png);
}
a#news:
{
background-image:url(news-normal.png);
margin-right:0px;
}
a#news:hover:
{
background-image:url(news-highlight.png);
}
#main,#news,#tips
{
background-repeat:no-repeat;
display:block;
text-decoration:none;
text-indent:-30000px;
}
When I hover over the image it does get change to highlighted image but when I click on the link the tab goes back to normal image. I want it to stay highlighted when the user is currently on that page. Can anyone help me with this?
I tried "visited" but it doesn't seem to work and everything I found on Google search was a little bit different than what I'm trying to do.
Thanks in advance.
To answer the specific question, when a user clicks a link, they are taken to a new page. The links have no concept in and of themselves as to what page they exist on.
So you have a few options. The common solution is to use server-side code to send HTML with some indicator that that is the current link. You could add a class like 'current' for example. Furthermore, if that is the page you are on, there's no need for the link either, so one should not have that text linked.
But if you don't have access to the server, then you need to add this manually. You could either create a new style for .current and then on that page, apply that class to your active link.
However, perhaps you are including this menu as an include...meaning the code is the same for every single page. In that case, you will want to target the active link with your CSS. So on each page you'd have a custom bit of CSS on the page.
On the tips page, for example, you'd do this:
#tips {put your style here for active links}
To get a bit fancier/more automated, you could write some javascript that would:
parse the URL
figure out the file name of the page
match that filename up to something in your list of links
apply the class for you dynamically
PS. there is no real need to use the syntax of a#tips in your CSS. The reason is that if you are using an id, there can only be one id on the page, so the a is somewhat redundant.
There are many ways to do this. With PHP, JavaScript or pure CSS with some extra markup.
Since you said you are new to HTML/CSS I think the CSS way would be best for you?
So you have 3 pages with exact the same menu code? Just put this on each site:
For your main page:
<div id="navigation">
<a id="main" class="active" href="domain.com/main">main</a>
<a id="tips" href="domain.com/tips">tips</a>
<a id="news" href="domain.com/news">news</a>
</div>
Your tips page:
<div id="navigation">
<a id="main" href="domain.com/main">main</a>
<a id="tips" class="active" href="domain.com/tips">tips</a>
<a id="news" href="domain.com/news">news</a>
</div>
Your news page:
<div id="navigation">
<a id="main" href="domain.com/main">main</a>
<a id="tips" href="domain.com/tips">tips</a>
<a id="news" class="active" href="domain.com/news">news</a>
</div>
Add CSS:
#main.active {background-image:url(main-highlight.png);}
#tips.active {background-image:url(tips-highlight.png);}
#news.active {background-image:url(news-highlight.png);}
This example works fine for me...
Home Page
<html>
<head>
<title>Home</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body#home a#homenav, body#second a#secondnav {
color: #f8f8f8;
background: #D34;
cursor: default;
}
</style>
</head>
<body id="home">
<nav>
<ul>
<li>Home</li>
<li>Second</li>
</ul>
</nav>
</body>
Second Page
<html>
<head>
<title>Second</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<style>
body#home a#homenav, body#second a#secondnav {
color: #f8f8f8;
background: #D34;
cursor: default;
}
</style>
<body id="second">
<nav>
<ul>
<li>Home</li>
<li>Second</li>
</ul>
</nav>
</body>
A way to highlight the navigation tab on the current page with CSS is to create an active class to append to the class of the tag you are currently on. Your active css class would detail how you want it to look when it's considered active. Then, depending on what tab you are on, you insert the active as class for that tab as seen below.
`
<html>
<head>
<title>Highlight Nav Tab of Page</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial- scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
</head>
<style>
.navbar {
background-color: purple;
font-size: 12px !important;
line-height: 1.42857143 !important;
}
.navbar li a, .navbar .navbar-brand {
color: #fff !important;
}
.navbar-nav li a:hover, .navbar-nav li.active a {
color: purple !important;
background-color: #fff !important;
}
</style>
<body id="about.html" data-spy="scroll" data-target=".navbar" data-offset="60">
<!--navbar-->
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container">
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav navbar-right">
<li >Home</li>
<li class = "active">About</li>
<li >More</li>
<li >Contact Us</li>
</ul>
</div>
</div>
</nav>
</body>
</html>
`
Image shows what nav highlight looks like

Categories

Resources