Javascript changes the format of my Div in HTML - javascript

I am new to JS, HTML and CSS. I was trying to build a car dealership-like website to practice what I have learned so far and I have come to this one single problem. I made a div that would simulate a user dropdown when triggered using JS method. The method I used is when the user clicked the word car brands list it would show up the hidden div. But what happens is that without JS my dropdown design is all good, but then when JS is inserted into the equation it formats it like how it looks like without any CSS in it. Here is a picture for reference. First one is how it should be, the second one is how it looks with JS in it. Please pardon my bad usage of the tools in stack overflow. I am also new here.
var carListDropdown = document.getElementById("car-brand-dropdown")
carListDropdown.style.display = "none";
function carListDrop(){
if(carListDropdown.style.display === "none"){
carListDropdown.style.display = "block";
} else {
carListDropdown.style.display = "none";
}
}
#car-brand-dropdown {
background: black;
height: 350px;
width: 500px;
color: white;
display: flex;
justify-content: space-around;
margin-right: 90px;
position: absolute;
border-radius: 5px;
margin-top: 2px;
transform: translateX(700px);
z-index: 1;
}
<div class="car-brand-list" onclick="carListDrop()">Car Brands</div>
<div id="car-brand-dropdown">
<ul class="car-brand-list-one">
<li>Aston Martin</li>
<li>Audi</li>
<li>Bentley</li>
<li>BMW</li>
<li>Chevrolet</li>
<li>Dodge</li>
<li>Fiat</li>
<li>Ford</li>
</ul>
<ul class="car-brand-list-two">
<li>Honda</li>
<li>Jaguar</li>
<li>Jeep</li>
<li>KIA</li>
<li>Lamborghini</li>
<li>Land Rover</li>
<li>Lexus</li>
<li>Lotus</li>
</ul>
<ul class="car-brand-list-three">
<li>Mazda</li>
<li>Mercedes-Benz</li>
<li>Mini</li>
<li>Mitsubishi</li>
<li>Nissan</li>
<li>Porsche</li>
<li>Subaru</li>
<li>Toyota</li>
<li>Volkswagen</li>
</ul>
</div>
How it should look like
How it looks with JS inserted into the program

Edit this
var carListDropdown = document.getElementById("car-brand-dropdown")
carListDropdown.style.display = "none";
function carListDrop(){
if(carListDropdown.style.display === "none"){
carListDropdown.style.display = "flex";
} else {
carListDropdown.style.display = "none";
}
}

I removed your entire JS as it is not needed. We can do it directly with the onclick-trigger
I changed the ID of the element to a class for specificty weight reasons.
I added a class (.none) that contains display: none; to hide that element.
I changed the onclick-trigger to document.querySelector('.car-brand-dropdown').classList.toggle('none');
document.querySelector('.car-brand-dropdown') will select your list just like getElementById just the modern statement that can be used to select calsses, ID, tags...
classList.toggle('none) will remove the class .none if the elemnt has this class and add it, if the element does not have this class. So no need for if/else-statments.
.car-brand-dropdown {
background: black;
height: 350px;
width: 500px;
color: white;
display: flex;
justify-content: space-around;
margin-right: 90px;
position: absolute;
border-radius: 5px;
margin-top: 2px;
transform: translateX(700px);
z-index: 1;
}
.none {
display: none;
}
<div class="car-brand-list" onclick="document.querySelector('.car-brand-dropdown').classList.toggle('none');">Car Brands</div>
<div class="car-brand-dropdown none">
<ul class="car-brand-list-one">
<li>Aston Martin</li>
<li>Audi</li>
<li>Bentley</li>
<li>BMW</li>
<li>Chevrolet</li>
<li>Dodge</li>
<li>Fiat</li>
<li>Ford</li>
</ul>
<ul class="car-brand-list-two">
<li>Honda</li>
<li>Jaguar</li>
<li>Jeep</li>
<li>KIA</li>
<li>Lamborghini</li>
<li>Land Rover</li>
<li>Lexus</li>
<li>Lotus</li>
</ul>
<ul class="car-brand-list-three">
<li>Mazda</li>
<li>Mercedes-Benz</li>
<li>Mini</li>
<li>Mitsubishi</li>
<li>Nissan</li>
<li>Porsche</li>
<li>Subaru</li>
<li>Toyota</li>
<li>Volkswagen</li>
</ul>
</div>

The "default" value for a Flex container uses column for direction whereas for your layout you really want to use row. The individual ul elements within the parent container can be left as block level items and the parent will have the flex properties assigned to it. With Javascript you can easily toggle the appearance of an item using classList.toggle ~ which saves using inline node.style.display=... type syntax as you can define the look far easier with CSS.
Rather than adding inline event handlers it is generally considered better practise to use an external event listener -done using addEventListener. This makes for cleaner HTML markup and when the event handlers are stored in an external file it means they can be referenced in other pages by including that script.
/* two utility functions to shorten querySelector calls */
const q=(e,n=document)=>n.querySelector(e);
const qa=(e,n=document)=>n.querySelectorAll(e);
/* find the HTML elements of interest */
const oDiv=q('.car-brand-list');
const oSel=q('#car-brand-dropdown');
/*
add an event handler that toggles the class of the `select` type div,
modifies the class of the clicked text and resets the dataset attribute
that displays the hyperlink text when clicked.
*/
oDiv.addEventListener('click',function(e){
oSel.classList.toggle('flex');
this.classList.toggle('active');
oDiv.dataset.brand='';
});
/*
assign a click handler to each hyperlink - the functionaliyt of the
hyperlinks is unclear but here it is used to display the brand selected.
*/
qa('ul[class^="car-brand"] > li > a').forEach( a=>a.addEventListener('click',function(e){
e.preventDefault();
oDiv.dataset.brand=this.textContent
}));
*{font-family:monospace;}
a{
color:white!important;
text-decoration:none;
}
.car-brand-list{
font-size:1.5rem;
padding:0.25rem;
cursor:pointer;
font-weight:bold;
width:100px;
}
.car-brand-list.active{
background:black;
color:white;
border-radius:0.25rem;
}
.car-brand-list:after{
content:" - "attr(data-brand);
color:gray;
}
[data-brand='']:after{
content:'';
}
#car-brand-dropdown {
background: black;
max-height:350px;
color: white;
display:none;
border-radius:1rem;
transition:ease-in-out all 250ms;
z-index: 1;
}
.car-brand-list,
#car-brand-dropdown{width:500px;}
.flex{
display:flex!important;
justify-content:space-around;
flex-direction:row;
flex-wrap:nowrap;
margin:0.25rem auto;
}
ul{
flex:1;
margin:1rem;
padding:1rem;
list-style:none;
}
ul li{
padding:0.1rem;
font-size:90%;
}
<div class='car-brand-list' data-brand>Car Brands</div>
<div id='car-brand-dropdown'>
<ul class='car-brand-list-one'>
<li><a href='#'>Aston Martin</a></li>
<li><a href='#'>Audi</a></li>
<li><a href='#'>Bentley</a></li>
<li><a href='#'>BMW</a></li>
<li><a href='#'>Chevrolet</a></li>
<li><a href='#'>Dodge</a></li>
<li><a href='#'>Fiat</a></li>
<li><a href='#'>Ford</a></li>
</ul>
<ul class='car-brand-list-two'>
<li><a href='#'>Honda</a></li>
<li><a href='#'>Jaguar</a></li>
<li><a href='#'>Jeep</a></li>
<li><a href='#'>KIA</a></li>
<li><a href='#'>Lamborghini</a></li>
<li><a href='#'>Land Rover</a></li>
<li><a href='#'>Lexus</a></li>
<li><a href='#'>Lotus</a></li>
</ul>
<ul class='car-brand-list-three'>
<li><a href='#'>Mazda</a></li>
<li><a href='#'>Mercedes-Benz</a></li>
<li><a href='#'>Mini</a></li>
<li><a href='#'>Mitsubishi</a></li>
<li><a href='#'>Nissan</a></li>
<li><a href='#'>Porsche</a></li>
<li><a href='#'>Subaru</a></li>
<li><a href='#'>Toyota</a></li>
<li><a href='#'>Volkswagen</a></li>
</ul>
</div>

you'd better use addEventListener, but not html onclick attr.
JS:
document.querySelector('.car-brand-list').addEventListener('click',function(){
carListDrop();
})

Related

Dropdown Menu using javascript, HTML and CSS

I can't seem to get this to work. I don't wanna put jQuery in yet. Just doing plain javascript. When I click on the image nothing happens. I need it to dropdown the navigation when I click the image. Edited my Javascript code. I added alert to show the current status of what class the toggle is using. But still I cant get to change it from header_navigation_mobile to header_navigation_mobile.is_open
This is my HTML CODE for the Clickable Image
<a href="#" onclick="toggleMenu()">
<img class="mobile_navigation_button" src="{{site.baseurl}}/assets/img/menu.svg"/>
</a>
This is the HTML for the drop down navigation
<div class="header_navigation_mobile">
<ul>
<li>HOME</li>
<li>ABOUT</li>
<li>CONTACT</li>
<li> </li>
<li> </li>
</ul>
</div>
Then my CSS For the Clickable Image to show the navigation
.header_navigation_mobile.is_open{
display: block;
transform: translateY(0%);
}
This is the CSS for the Clickable Image first state which is to Hide it
.header_navigation_mobile{
display: none;
position: absolute;
width: 290px;
background: #484547;
transform: translateY(-100%);
transition: all 0.3s ease-in-out;
}
Then finally my Javascript
function toggleMenu(){
var mobileNav = document.getElementById('mobile_Nav');
var mobileNav_toggle = mobileNav.getAttribute("class");
if(mobileNav_toggle == "header_navigation_mobile") {
mobileNav_toggle == "header_navigation_mobile.is_open";
}
else {
mobileNav_toggle == "header_navigation_mobile";
}
alert(mobileNav_toggle);
}
I would give the menu an ID so it's easier to target, then just toggle a class that you use to hide/show the menu.
.header_navigation_mobile {
display: none;
}
.open {
display: block;
}
toggle
<div class="header_navigation_mobile" id="mobilenav">
<ul>
<li>HOME</li>
<li>ABOUT</li>
<li>CONTACT</li>
<li>
</li>
<li>
</li>
</ul>
</div>
<script>
function toggleMenu(){
var nav = document.getElementById('mobilenav');
nav.classList.toggle('open');
}
</script>
In your JS try like this.use querySelector for selecting elements.And for setting and getting css properties use selector.style.property_name.
function toggleMenu(){
var mobileNav_Hide = document.querySelector('.header_navigation_mobile');
var mobileNav_Show = document.querySelector('.header_navigation_mobile.is_open')
if(mobileNav_Hide.style.display == "none"){
mobileNav_Show.stylr.display == "block";
}
else{
mobileNav.style.display = "none";
}
}
I know this is not a specific answer to your question but may be a handy solution as well. I put together a jsfiddle of a hidden menu you can easily edit to your needs. Here is the link.
#Btn{
position: fixed;
right: 20px;
width: 20px;
height: 24px;
background: linear-gradient(#FFF,#DDD);
border: #AAA 1px solid;
border-radius: 2px;
padding: 2px 5px;
cursor: pointer;
transition: border 0.3s linear 0s;
}
#Btn:hover{
border: #06F 1px solid;
}
#Btn:hover div{
background: #06F;
}
#Btn > div{
width: 20px;
height: 4px;
background: #333;
margin: 3px 0px;
border-radius: 4px;
transition: background 0.3s linear 0s;
}
#hidden{
position: fixed;
right: -300px;
top: 60px;
width: 260px;
height: 0px;
background: #333;
color:#ededed;
padding:15px;
transition: right 0.3s linear 0s;
}
<script>
function toggleBTN(){
var hidden = document.getElementById("hidden");
hidden.style.height = window.innerHeight - 60+"px";
if(hidden.style.right == "0px"){
hidden.style.right = "-300px";
} else {
hidden.style.right = "0px";
}
}
</script>
<div id="Btn" onclick="toggleBTN()">
<div></div>
<div></div>
<div></div>
</div>
<div id="hidden">
<ul>
<li>MENU ITEM 1</li>
<li>MENU ITEM 2</li>
<li>MENU ITEM 3</li>
</ul>
</div>
<div id="page_content">
<script>
for(var i = 0; i < 10; i++){ document.write("<h2>"+(i+1)+". Dummy page content ... </h2>"); }
</script>
</div>
Hope this helps :)
There are a few things in the else statement where is mobileNav coming from there is no instance of that anywhere in your code. Taking a step back a minute from your solution does the adding and removal of the classname is_open define the entire show hide behaviour you desire?
Your process of getting the same element with the subclass present/not present and then trying to set the display property is confusing.
You have an equality comparer when setting the display property when it should be just a single equals which along with my first statement i think is your main problem.
Instead of the way you are doing it i would just look at toggling the is_open class this link Toggle class on HTML element without jQuery shows how to do that and also demonstrates a few other ways of toggling styles including without javascript
Finally just check because im being lazy that display is valid as a property and that it shouldnt instead be style.display as others have indicated
js
let c = document.getElementById("dropdownlist");
let e = document.getElementById("dropdownicon");
let d = e.classList.toggle('fa-angle-down');
if(d===true) {
if(c.style.display==='none'){
c.style.display = 'block';
}
else{
c.style.display ='block';
}
}
else{
c.style.display = 'none';
}

How to make a menu remain active after clicking it? [duplicate]

In a page with some navigation links,I want the link of the current page are hightlighted,just like this:
The link "HTML Attributes" is highlighted(bolded) since this link will take one to the current page.
I know this can be implemented manually(just hightlighted the according link,but is there some smart way? highlight the right link dynamically and automatically?
CSS:
.topmenu ul li.active a, .topmenu ul li a:hover {
text-decoration:none;
color:#fff;
background:url(../images/menu_a.jpg) no-repeat center top;
}
JavaScript:
<script src="JavaScript/jquery-1.10.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
// this will get the full URL at the address bar
var url = window.location.href;
// passes on every "a" tag
$(".topmenu a").each(function() {
// checks if its the same on the address bar
if (url == (this.href)) {
$(this).closest("li").addClass("active");
//for making parent of submenu active
$(this).closest("li").parent().parent().addClass("active");
}
});
});
</script>
Html Code:
<div class="topmenu">
<ul>
<li>Home</li>
<li>Newsletter</li>
<li>Forms</li>
<li>Mail</li>
<li>Service</li>
<li style="border:none;">HSE</li>
<li>MainMenu2
<ul>
<li>submenu1</li>
<li>submenu2</li>
<li>submenu3</li>
</ul>
</li>
</ul>
</div>
You can set the id of the body of the page to some value that represents the current page. Then for each element in the menu you set a class specific to that menu item. And within your CSS you can set up a rule that will highlight the menu item specifically...
That probably didn't make much sense, so here's an example:
<body id="index">
<div id="menu">
<ul>
<li class="index" >Index page</li>
<li class="page1" >Page 1</li>
</ul>
</div> <!-- menu -->
</body>
In the page1.html, you would set the id of the body to: id="page1".
Finally in your CSS you have something like the following:
#index #menu .index, #page1 #menu .page1 {
font-weight: bold;
}
You would need to alter the ID for each page, but the CSS remains the same, which is important as the CSS is often cached and can require a forced refresh to update.
It's not dynamic, but it's one method that's simple to do, and you can just include the menu html from a template file using PHP or similar.
It seems to me that you need current code as this ".menu-current css", I am asking the same code that works like a charm, You could try something like this might still be some configuration
a:link, a:active {
color: blue;
text-decoration: none;
}
a:visited {
color: darkblue;
text-decoration: none;
}
a:hover {
color: blue;
text-decoration: underline;
}
div.menuv {
float: left;
width: 10em;
padding: 1em;
font-size: small;
}
div.menuv ul, div.menuv li, div.menuv .menuv-current li {
margin: 0;
padding: 0;
list-style: none;
margin-bottom: 5px;
font-weight: normal;
}
div.menuv ul ul {
padding-left: 12px;
}
div.menuv a:link, div.menuv a:visited, div.menuv a:active, div.menuv a:hover {
display: block;
text-decoration: none;
padding: 2px 2px 2px 3px;
border-bottom: 1px dotted #999999;
}
div.menuv a:hover, div.menuv .menuv-current li a:hover {
padding: 2px 0px 2px 1px;
border-left: 2px solid green;
border-right: 2px solid green;
}
div.menuv .menuv-current {
font-weight: bold;
}
div.menuv .menuv-current a:hover {
padding: 2px 2px 2px 3px;
border-left: none;
border-right: none;
border-bottom: 1px dotted #999999;
color: darkblue;
}
<script id="add-active-to-current-page-nav-link" type="text/javascript">
function setSelectedPageNav() {
var pathName = document.location.pathname;
if ($("nav ul li a") != null) {
var currentLink = $("nav ul li a[href='" + pathName + "']");
currentLink.addClass("active");
}
}
setSelectedPageNav();
</script>
Css classes are here
<style type="text/css">
.mymenu
{
background-color: blue;
color: white;
}
.newmenu
{
background-color: red;
color: white;
}
</style>
Make your HTML like this, Set url as id
<div class="my_menu" id="index-url">Index</div>
<div class="my_menu" id="contact-url">Contac</div>
Here write javascript, put this javascript after the HTML code.
function menuHighlight() {
var url = window.location.href;
$('#'+tabst).addClass('new_current');
}
menuHighlight();
I would normally handle this on the server-side of things (meaning PHP, ASP.NET, etc). The idea is that when the page is loaded, the server-side controls the mechanism (perhaps by setting a CSS value) that is reflected in the resulting HTML the client sees.
You can use Javascript to parse your DOM, and highlight the link with the same label than the first h1 tags. But I think it is overkill =)
It would be better to set a var wich contain the title of your page, and use it to add a class at the corresponding link.
I usually use a class to achieve this. It's very simple to implement to anything, navigation links, hyperlinks and etc.
In your CSS document insert:
.current,
nav li a:hover {
/* styles go here */
color: #e00122;
background-color: #fffff;
}
This will make the hover state of the list items have red text and a white background. Attach that class of current to any link on the "current" page and it will display the same styles.
Im your HTML insert:
<nav>
<ul>
<li class="current">Nav Item 1</li>
<li>Nav Item 2</li>
<li>Nav Item 3</li>
</ul>
</nav>
Please Look at the following:
Here is what's working:
1.) top menu buttons are visible and highlight correctly
2.) sub menu buttons are not visible until top menu is clicked
Here is what needs work:
1.) when sub menu is clicked, looking for new page to keep the selected sub menu open (i will highlight the selected sub menu button for further clarification on navigation)
Please see code here:
http://jsbin.com/ePawaju/1/edit
or here:
http://www.ceramictilepro.com/_6testingonly.php#
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
Do I need to put this script in the head section? Where is the best place?
<div class="left">
<nav class="vmenu">
<ul class="vnavmenu">
<li data-ref="Top1"><a class="hiLite navBarButton2" href="#">Home</a>
</li>
</ul>
<ul class="Top1 navBarTextSize">
<li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">sub1</a>
</li>
<li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">sub2</a>
</li>
<li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">sub3</a>
</li>
<li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">sub4</a>
</li>
</ul>
<ul class="vnavmenu">
<li data-ref="Top2"><a class="hiLite navBarButton2" href="#">Repairs</a>
</li>
</ul>
<ul class="Top2 navBarTextSize">
<li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">1sub1</a>
</li>
<li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">2sub2</a>
</li>
<li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">3sub3</a>
</li>
<li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">4sub4</a>
</li>
</ul>
</nav>
JQuery is new to me, any help would greatly be appreciated :)
var submenu;
$('.vnavmenu li').click(function () {
var elems = $('.vmenu ul:not(.vnavmenu)').length;
var $refClass = $('.' + $(this).attr('data-ref'));
var visible = $refClass.is(':visible');
$('.vmenu ul:not(.vnavmenu)').slideUp(100, function () {
if (elems == 1) {
if (!visible) $refClass.slideDown('fast');
}
elems--;
});
if (visible) $('#breadcrumbs-pc').animate({
'margin-top': '0rem'
}, 100);
else $('#breadcrumbs-pc').animate({
'margin-top': '5rem'
}, 100);
});
JavaScript:
<script type="text/javascript">
$(function() {
var url = window.location;
$('ul.nav a').filter(function() {
return this.href == url;
}).parent().parent().parent().addClass('active');
});
</script>
CSS:
.active{
color: #fff;
background-color: #080808;
}
HTML:
<ul class="nav navbar-nav">
<li class="dropdown">
<i class="glyphicon glyphicon-user icon-white"></i> MY ACCOUNT <span class="caret"></span>
<ul class="dropdown-menu" role="menu">
<li>
<?php echo anchor('myaccount', 'HOME', 'title="HOME"'); ?>
</li>
<li>
<?php echo anchor('myaccount/credithistory', 'CREDIT HISTORY', 'title="CREDIT HISTORY"'); ?>
</li>
</ul>
</li>
</ul>
I prefer to keep code as short and plain as possible, and avoid using any external files (jquery included).
So here is what I've ended up with for myself after researching several topics - using plain Javascript and CSS, no need for jquery.
Put javascript code right after the menu finishes (after closing ul, div, whatever) - code from a snippet should be between <script>Copy code here</script>
That would allow for a script to execute right after menu will be loaded.
If you want to call it as a function on page load, then link will change only after all elements (including images) are loaded – place this code in a function, call it on page load, the code itself put before the closing tag like so:
<script>
function highlightCurrentURL() {
var a = document.getElementById("navig").getElementsByTagName("a");
for (var i = 0; i < a.length; i++) {
if (a[i].href.split("#")[0] == document.location.href.split("#")[0]) {
a[i].className = "current";
}
}
}
//
window.onload = function() {
highlightCurrentURL();
}
</script>
// restrict search to a parent with specific ID (main), rather than search in the whole document
var a = document.getElementById("navig").getElementsByTagName("a");
console.log("Current URL: ", document.location.href.split("#")[0]);
console.log("Links found in HTML: ");
for (var i = 0; i < a.length; i++) {
// for debugging you can check all found URLs in console (accessible in development mode) and delete next line after debugging
console.log(a[i].href);
// strip off any local (withing page) anchors (symbol "#" and what follows after)
if (a[i].href.split("#")[0] == document.location.href.split("#")[0]) {
// add a class to the matched link (<a>), define it in CSS
a[i].className = "current";
}
}
nav#navig a.current {
color: red;
}
<nav id="navig">
<ul>
<li>url1 name</li>
<li>url2 name</li>
<li>url3 name</li>
<li>Test link matching current URL</li>
</ul>
</nav>
You can Implement this in various ways usinh PHP or Jquery. Here is how I have implemented it in my Projects.
<?php
//set a default value when the page is not an active page
$dashboard_active=$profile_active=$home_active='inactive_page';
//get the Name of the current page;
//in simple php set the NAME of the php file similar to the link variable
//example set page name as home if you are going to print the variable $home/$home_active
$page = pathinfo($_SERVER['PHP_SELF'], PATHINFO_FILENAME);
//OR
//in Laravel
$page=Route::currentRouteName();
//OR
//send page value from the controller
${$page."_active"} = 'active_page';
//the above method will change the value of the current active page variable
?>
In html print the php data
<ul class="nav navbar-nav ">
<li ><span class=" <?php echo $dashboard_active ?> "> Dashboard</span></li>
<li ><span class=" <?php echo $profile_active ?>"> Profile</span></li>
<li ><span class=" <?php echo $home_active ?>">Home</span></li>
</ul>
YOu can also do this with Jquery
<script>
//with jquery
$(function(){
//works when your href is an absolute href instead of relative href
$('a').each(function(){
if ($(this).prop('href') == window.location.href) {
$(this).children('span').addClass('active_page');
//to make the link only active
$(this).addClass('active_page');
//to make the list active
$(this).panrent('li').addClass('active_page');
}
});
});
</script>
IN the CSS you need to add this
<style>
.active_page:hover,.inactive_page:hover
{
background-color: rgb(218, 119, 5)!important;
color: white;
}
.active_page
{
background-color: green!important;
color: white!important;
}
.inactive_page
{
color:#fff;
}
</style>

Multiple images depending on mouse location when hovering over div

I am trying to do an overview page on my website so that when I hover over a div on the overview page different sections of that div show different images. Essentially a slideshow but the image changes depending on where the cursor is.
I have managed to find some code that does what I want but it uses an a href to pull in the images which means if you click it, it goes to the link of the image.
Currently I just have placeholder images in but when finished each one will have specific project images in. As each div will just be one project the whole div should go to one html link and not just a specific image link of the image the user is hovering over.
All I want is the user to click and it go to a html link and not an img link.
Here is the code I am using:
The coding savvy people out there will probably have a much better solution for what I would like to achieve, I am interested to see any better solutions.
HTML
<div class="multi">
<ul class="rotator-nav fifth clearfix">
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
<div class="imgcontent">
<ul class="rotator-icons fifth">
<span class="img1 active"></span>
<span class="img2"></span>
<span class="img3"></span>
<span class="img4"></span>
<span class="img5"></span>
</ul>
<img src="/img/FoI.jpg" class="currentimg">
</div>
</div>
CSS
.multi {
display: block;
float:left;
position: relative;
width: 30.8%;
height: 20%;
padding: 0px;
margin:0% 1% 2% 1%;
overflow: hidden;
}
.multi .imgcontent {
display: block;
position: absolute;
top: 0px;
}
.imgcontent img {
display:block;
width: 100%;
height: auto;
margin-left: auto;
margin-right: auto;
}
.rotator-nav {
display: block;
position: relative;
width: 100%;
height: 100%;
z-index: 9;
}
.rotator-nav li {
display: block;
float: left;
height: 100%;
}
.rotator-nav.fourth li {
width: 25%;
}
.rotator-nav.fifth li {
width: 20%;
}
.rotator-nav li a {
display: block;
float: left;
width: 100%;
height: 100%;
border-bottom:0px solid #fff
}
.clearfix:after { content: "."; display: block; clear: both; visibility: hidden; line-height: 0; height: 0; }
.clearfix { display: inline-block; }
html[xmlns] .clearfix { display: block; }
* html .clearfix { height: 1%; }
JS
$(function(){
var $rotators = $('.multi');
var $imglinks = $('.rotator-nav a');
$imglinks.on('mouseenter', function(e){
var imgclass = '.'+$(this).attr('class');
var imglink = $(this).attr('href');
// update main image src
$(this).parent().parent().parent().find('.currentimg').attr('src',imglink);
// update current rotator icon
var $rotators = $(this).parent().parent().parent().find('.rotator-icons');
if($rotators.children(imgclass).hasClass('active')) {
// already active icon -- do nothing
} else {
// remove active class then add to new icon
$rotators.children('span').removeClass('active');
$rotators.children(imgclass).addClass('active');
}
});
});
Any help would be greatly appreciated!
Thanks,
Mark
I think you could best use a data attribute for this instead (if I understand the intention correctly) :
var imglink = $(this).data('image');
<div class="multi">
<ul class="rotator-nav fifth clearfix">
<li>
<a data-image="/img/FoI.jpg" href="#" class="img1"></a>
</li>
<li>
<a data-image="/images/card.jpg" href="#" class="img2"></a>
</li>
<li>
<a data-image="/images/amareal.jpg" href="#" class="img3"></a>
</li>
<li>
<a data-image="/images/edeva.jpg" href="#" class="img4"></a>
</li>
<li>
<a data-image="/images/amacover2.gif" href="#" class="img5"></a>
</li>
</ul>
...
If you'd still like to see the image over the original div, a pseudo element could be used. Advantage there is that they are not actual DOM elements and will not register clicks :
Demo
Now it would be great if the data attribute could be directly used for the content of the pseudo element as well but that doesn't seem possible. And you can't target them with JavaScript so each image would have to be defined with nth-of-type() in the stylesheet additionally.
You don't need to use .parent().parent()
Just use the parent's class to find the item.
Your $(this).parent() * 3 is the $(".multi")
So your $rotators can't find .rotator-icons,
you need to use one more parent or use siblings
And I suggest do not use class if there are no need to do one thing to lots of items.

Replace main navigation links with submenu links on hover - instead of a dropdown

I recently saw a navigation effect I liked on a website, but can't find it to check the code and see how it was done. There was a standard menu bar that was 100% width and aprox 30px in height, with each link equally spaced within it. When you hovered on the gallery link the whole menu bar changed and the links were replaced with the submenu. No dropdown, the whole menu bar was changed to the submenu items. I can't quite sort out how this was done. Any suggestions would be appreciated. Here is the example html markup I am working with:
<nav>
<ul class ="menu">
<li class ="nav__item">about</li>
<li class ="nav__item">galleries
<ul class="submenu">
<li class ="nav__subitem">one</li>
<li class ="nav__subitem">two</li>
<li class ="nav__subitem">three</li>
<li class ="nav__subitem">four</li>
<li class ="nav__subitem">five</li>
<li class ="nav__subitem">six</li>
</ul> <!-- close sub -->
</li>
<li class ="nav__item">stories</li>
<li class ="nav__item">contact</li>
<li class ="nav__item">thank you</li>
</ul>
</nav>
Not sure if this is what you are looking for but check out this fiddle
Setting a fixed height to the navigation with relative positioning and targeting the parent of the nested ul on mouse over I was able to achieve this effect.
nav {
height: 50px;
overflow: hidden;
position: relative;
background: #999999;
}
.menu {
list-style-type:none;
position: relative;
}
ul {
padding: 0;
margin: 0;
}
li.nav__item {
float:left;
}
li.nav__item a {
padding: 0 15px;
line-height:50px;
}
.submenu {
position:absolute;
left:15px;
}
.nav__subitem {
line-height: 50px;
float: left;
list-style: outside none none;
}
And the little bit of jQuery magic to tie it all together.
$(".has-children").mouseover(function () {
$(".menu").css("top", "-50px");
});
$(".main-navigation").mouseleave(function () {
$(".menu").css("top", "0px");
});

cannot make list item visible with > CSS selector

I'm unable to make the popups 'redItem', 'blueItem' and 'greenItem' below visible again after setting their display to 'none'. I'm using a CSS selector to get them visible again when the mouse hovers over a node higher up in the nested list to no avail.
Here's the code:
<ul class="popups" style="vertical-align: bottom; padding: 0px; margin: 0px;">
<li style="width: 165px"><a id="topmostBox" href="#">One_high-up_item</a>
<ul class="popups">
<li>First-lower-item
<ul class="popups">
<li name="redItem" >Red</li>
<li name="blueItem">Blue</li>
<li name="greenItem">Green</li>
</ul>
</li>
</ul>
</li>
</ul>
.popups:hover > li {
display: block;
}
.popups {
background-color: white;
font-family: sans-serif;
font-size: 13.5px;
list-style: none;
position: relative;
border: 1px solid lightgray;
border-width: .05em;
border-top-color: rgb(165,165,165);
line-height: 1.2em;
display: inline-table;
}
function setTopColorAndVis(theNestedPopupAnchor)
{
var theColorName = theNestedPopupAnchor.innerHTML;
var topMenuBox = document.getElementById('topmostBox');
topMenuBox.innerHTML = theColorName ;
theNestedPopupAnchor.parentNode.style.display = "none";
}
What happens is this:
1) I select the color 'Red' (the 1st list item)
2) my call to setTopColorAndVis(this) makes the popup disappear (because the user selected an item, the color "Red", and now the popup is not needed for now)
3) but when I later hover the mouse over the "First-lower-item" list item, the child li that has the ul containing 'redItem', 'greenItem', 'blueItem' does not appear.
So my experience here is that I'm successfully able to hide the list items named 'redItem', 'blueItem' and 'greenItem' -- but when I hover over the "First-lower-item", despite my CSS code:
.popups:hover > li {
display: block;
}
The 'redItem', 'greenItem' and 'blueItem' do NOT reappear.
What am I missing here?
The inline style overrides you style in your css code. you should use onmouseover event and onmouseout instead.
Try
<li name="redItem" >Red</li>
function show(elem){
elem.parentNode.style.display = "block";
}
function hide(elem){
elem.parentNode.style.display = "none";
}
You cannot :hover over an element with display:none as it has no size...
instead of working with display, you can work with visibility - which will leave an area to hover over.
like so:
theNestedPopupAnchor.parentNode.style.visibility = 'hidden'
.popups:hover > li {
visibility: visible;
}
http://www.w3schools.com/cssref/pr_class_visibility.asp

Categories

Resources