I want to change a button color when click the button. This is the code that I used.
function abc() {
var color = document.getElementById("btn").style.background - color;
if (background - color === "#c1580b")
document.getElementById("btn").style.cssText = "box-shadow: 0px 0px 0px 3px #173B0B; background-color: #173B0B; color:#459c5c";
else
document.getElementById("btn").style.cssText = "box-shadow: 0px 0px 0px 3px #c1580b; background-color: #c1580b; color:#ffb734";
}
.btn {
background: #c1580b;
color: #ffb734;
width: 80px;
height: 80px;
line-height: 70px;
display: block;
border-radius: 50%;
text-align: center;
text-decoration: none;
border: 2px solid #000;
box-shadow: 0px 0px 0px 3px #c1580b;
font-size: medium;
}
<button id="btn" class="btn" onclick="abc()">Pause</button>
But this is not working.
I did not quite understand that part of the background - color, but to check the background in hex, you have to go from hex to rgb.
Can see here more examples of how to pass hex to rgb - https://stackoverflow.com/a/4090628/8098173
Here's an example of what you want.
function abc() {
var bt = document.getElementById('btn');
var style = bt.currentStyle || window.getComputedStyle(bt);
var bcolor = rgb2hex(style.backgroundColor);
if (bcolor === '#c1580b') {
bt.style.cssText = "box-shadow: 0px 0px 0px 3px #173B0B; background-color: #173B0B; color:#459c5c";
} else {
bt.style.cssText = "box-shadow: 0px 0px 0px 3px #c1580b; background-color: #c1580b; color:#ffb734";
}
}
// pass rbg to hex
function rgb2hex(rgb) {
if ( rgb.search("rgb") == -1 ) {
return rgb;
} else {
rgb = rgb.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+))?\)$/);
function hex(x) {
return ("0" + parseInt(x).toString(16)).slice(-2);
}
return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}
}
.btn {
background: #c1580b;
color: #ffb734;
width: 80px;
height: 80px;
line-height: 70px;
display: block;
border-radius: 50%;
text-align: center;
text-decoration: none;
border: 2px solid #000;
box-shadow: 0px 0px 0px 3px #c1580b;
font-size: medium;
}
<button id="btn" class="btn" onclick="abc()">Pause</button>
Here you have a working code.
I would suggest you to avoid the inline onclick="abc()" and opt in favor of a fully-separated code using EventListener (that's good for maintainability).
With Window.getComputedStyle() you get the background color in RGBA; you can then convert it to the HEX code with a simple function that you can find everywhere on the Web, here I used one of them. So, the right way to get the background color is window.getComputedStyle(btn, null)["backgroundColor"] while, if you would like to set it, the correct form would be document.getElementById("btn").style.backgroundColor = "#0000".
/**
* The code inside the function is run only when the DOM is ready.
* This is the only jQuery function used, all the rest is in vanillaJS.
*/
$(document).ready(function() {
/**
* rgb2hex
* Convert RGB to HEX.
* Source: https://jsfiddle.net/Mottie/xcqpF/1/light/
*
* #param {string} rgb
*/
var rgb2hex = function(rgb){
rgb = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
return (rgb && rgb.length === 4) ? "#" +
("0" + parseInt(rgb[1],10).toString(16)).slice(-2) +
("0" + parseInt(rgb[2],10).toString(16)).slice(-2) +
("0" + parseInt(rgb[3],10).toString(16)).slice(-2) : '';
}
/**
* EventListener of btn click event
*/
document.getElementById("btn")
.addEventListener('click', function() {
// Save the btn into a var so you can use it later
var btn = document.getElementById("btn");
// Notice: getComputedStyle() to get the element background color
var color = window.getComputedStyle(btn, null)["backgroundColor"];
// Transform RGBa to HEX
var hex = rgb2hex(color);
// IF-ELSE with ternary operators
(hex === "#c1580b")
? btn.style.cssText = "box-shadow: 0px 0px 0px 3px #173B0B; background-color: #173B0B; color:#459c5c"
: btn.style.cssText = "box-shadow: 0px 0px 0px 3px #c1580b; background-color: #c1580b; color:#ffb734";
});
});
.btn {
background: #c1580b;
color: #ffb734;
width: 80px;
height: 80px;
line-height: 70px;
display: block;
border-radius: 50%;
text-align: center;
text-decoration: none;
border: 2px solid #000;
box-shadow: 0px 0px 0px 3px #c1580b;
font-size: medium;
cursor: pointer;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<button id="btn" class="btn">Pause</button>
</body>
</html>
if always you use this color in HEX format (#c1580b), So:
function abc() {
var elm = document.getElementById( 'btn' );
var color = window.getComputedStyle( elm ).backgroundColor;
if ( color === 'rgb(193, 88, 11)' )
elm.style.cssText = 'box-shadow: 0 0 0 3px #173B0B; background-color: #173B0B; color: #459c5c'
else
elm.style.cssText = 'box-shadow: 0 0 0 3px #c1580b; background-color: #c1580b; color: #ffb734'
}
Your code contains some logical error. The if condition has no sense : background - color means «substract the value of color to the value of background (which seems to be undefined).
To get the background color of the button, you need the following
background = document.getElementById("btn").style.backgroundColor;
if (background === "#c1580b")
Related
I'm trying to make a simple comment system. It display comments, but when I refresh the page , all comments disappear, only to re-appear again when I add a new comment. I would like to see the comments even after refreshing the page. And preferably with time stamp and in reverse order: so latest on top.
const field = document.querySelector('textarea');
const comments = document.getElementById('comment-box');
// array to store the comments
var comments_arr = [];
if(!localStorage.commentData){localStorage.commentData = [];}
else{
comments_arr = JSON.parse(localStorage.commentData);
}
// to generate html list based on comments array
const display_comments = () => {
let list = '<ul>';
comments_arr.forEach(comment => {
list += `<li>${comment}</li>`;
})
list += '</ul>';
comments.innerHTML = list;
}
submit.onclick = function(event){
event.preventDefault();
const content = field.value;
if(content.length > 0){ // if there is content
// add the comment to the array
comments_arr.push(content);
localStorage.commentData = JSON.stringify(comments_arr);
// re-genrate the comment html list
display_comments();
// reset the textArea content
field.value = '';
}
}
html {
font-size: 14px;
font-family: "Open Sans", sans-serif;
background-color: rgb(239, 239, 238);
}
/*Comment section*/
textarea {
margin: 40px 0px 10px 0px;
background-color: rgb(255, 255, 255);
width: 800px;
padding: 10px;
line-height: 1.5;
border-radius: 5px;
border: 1px solid #7097d1;
box-shadow: 1px 1px 1px #999;
}
#submit {
border-radius: 5px;
border: 1px solid #7097d1;
background-color: #e2e9ea;
}
#submit:hover {
background-color: #7097d1;
}
li {
list-style-type: none;
width: 770px;
margin: 10px 0px 10px -20px;
padding: 5px;
border-radius: 5px;
border: 1px solid #7097d1;
box-shadow: 1px 1px 1px #999;
background-color: #e2e9ea;
}
<link href="comment.css" rel="stylesheet">
<form>
<textarea id="comment" placeholder="Your response pls." value=""></textarea>
</form>
<input id="submit" type="submit" value="add">
<h4>Responses</h4>
<div id="comment-box"></div>
<script src="comment.js"></script>
Adding window.addEventListener('load', display_comments) will fix
This will run the display_comments function on every refresh
You call display_comments after submitting a comment, but you don't call it anywhere else - it needs to be called when the page loads as well.
I am making a hang man game.
I created a randomWord using an array and a censoredWord, which is the randomWord but all its letters are hidden using "_" except the first and last.
I also have a lettersToGuess variable, used to know all the letters to guess, (I created it by simply slicing off the first and the last letter of the randomWord), and every time I guess a letter, that specific letter gets replaced with a " " in the lettersToGuess variable.
Now all works, but the problem is that when I guess a letter it just shows me the first of the censored ones.
For example, if the randomWord is "fish", the censoredWord would be "f__h", and if I click "i" on the keyboard the word will change in "fi_h", but if I click the "s" instead of the "i", it won't change to "f_sh".
Here is my code:
// Generating a random word
var wordsArray = ["cat", "rock", "sheep", "fish", "house"];
var randomWord = wordsArray[Math.floor(Math.random() * wordsArray.length)]; // Random word from wordsArray
var censoredWord = randomWord[0] + "_".repeat(randomWord.length - 2) + randomWord[randomWord.length - 1]; // Censored word created by using "_"
var lettersToGuess = randomWord.slice(1).slice(0, -1); // removing first and last letter
// Writing the word to web page
var randomWordOutput = document.getElementById("randomWord");
randomWordOutput.innerHTML = censoredWord;
// Function used to replace a letter of a string in a specific position
String.prototype.replaceAt = function (index, replacement) {
return this.substr(0, index) + replacement + this.substr(index + replacement.length);
}
// Function used to set the guessed letter to visible
function setCharVisible(censored, notCensored, index) {
for (i=1; i<censored.length-1; i++) {
if (index == i) {
console.log("guessed: " + notCensored[i]);
censored = censored.replaceAt(i, notCensored[i]);
}
}
return censored;
}
// Function used to know if the clicked letter is right
function checkForLetter(clickedId) {
var clickedLetter = document.getElementById(clickedId).textContent;
var clickedLetterButton = document.getElementById(clickedId);
console.log(lettersToGuess);
for (i in lettersToGuess) {
if (lettersToGuess[i] == clickedLetter) {
// Updating letters to guess variable
lettersToGuess = lettersToGuess.replace(clickedLetter, " ");
// Updating censored word removing "_" at the guessed letter position
censoredWord = setCharVisible(censoredWord, randomWord, i+1);
console.log(censoredWord);
// Set the clicked letter button to disabled
clickedLetterButton.classList.remove("keyboard-button");
clickedLetterButton.classList.add("guessed-disabled-button");
// Updating displayed censored word
randomWordOutput.innerHTML = censoredWord;
checkForWin(lettersToGuess);
}
}
}
// Checking for win function
function checkForWin(letters) {
guessedLettersSpaces = " ".repeat(lettersToGuess.length);
if (letters === guessedLettersSpaces) {
randomWordOutput.style.color = "#0cc206";
setTimeout(() => {
if (confirm("WIN")) {
window.location.reload();
}
}, 500);
}
}
* {
box-sizing: border-box;
font-family: Rubik, sans-serif;
}
body {
margin: 0;
padding: 0;
font-size: 16px;
background-color: #131313;
color: white;
}
.game-container {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: #0c0c0c;
padding: 50px;
border-radius: 40px;
}
#randomWord {
text-align: center;
padding: 20px;
}
.keyboard-container {
width: 900px;
display: block;
margin: auto auto;
}
.keyboard-button {
box-sizing: border-box;
line-height: 80px;
font-size: 22px;
text-align: center;
width: 80px;
color: #ffffff;
cursor: pointer;
margin: 10px 8px;
height: 80px;
border-style: solid #0c0c0c;
box-shadow: 0 0.5px 1px #0c0c0c, 0 2px 6px #0c0c0c;
border-width: 1px;
border-radius: 10px;
background: -webkit-linear-gradient(top, #141414 0%, #0f0f0f 80%, #0e0e0e 100%);
font-family: sans-serif;
display: inline-block;
transition: box-shadow 0.3s ease, transform 0.15s ease;
}
.keyboard-button:hover,
:focus {
box-shadow: 0 0 1px #888, 0 1px 0 #fff, 0 4px 0 #C0C0C0, 0 2px 35px rgba(#444, 0.3), 2px 2px 4px rgba(#444, 0.25), -2px 2px 4px rgba(#444, 0.25), 0 7px 4px rgba(#444, 0.1);
transform: translateY(2px);
}
.keyboard-button:active {
box-shadow: 0 0 1px #888, 0 1px 0 #fff, 0 0 0 #C0C0C0, 0 0px 30px rgba(#444, 0.15), 2px 2px 4px rgba(#444, 0.25), -2px 2px 4px rgba(#444, 0.25), 0 0px 4px rgba(#444, 0.25);
transform: translateY(4px);
}
.guessed-disabled-button {
box-sizing: border-box;
line-height: 80px;
font-size: 22px;
text-align: center;
width: 80px;
color: #0cc206;
margin: 10px 8px;
height: 80px;
border-style: solid #0c0c0c;
box-shadow: 0 0.5px 1px #0c0c0c, 0 2px 6px #0c0c0c;
border-width: 1px;
border-radius: 10px;
background: #222222;
font-family: sans-serif;
display: inline-block;
transition: box-shadow 0.3s ease, transform 0.15s ease;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./style/main.css">
<title>Hangman Game</title>
</head>
<body>
<div class="game-container">
<p id="randomWord"></p>
<div class="keyboard-container">
<div class="keyboard-button" id="key-a" onClick="checkForLetter(this.id)">a</div>
<div class="keyboard-button" id="key-b" onClick="checkForLetter(this.id)">b</div>
<div class="keyboard-button" id="key-c" onClick="checkForLetter(this.id)">c</div>
<div class="keyboard-button" id="key-d" onClick="checkForLetter(this.id)">d</div>
<div class="keyboard-button" id="key-e" onClick="checkForLetter(this.id)">e</div>
<div class="keyboard-button" id="key-f" onClick="checkForLetter(this.id)">f</div>
<div class="keyboard-button" id="key-g" onClick="checkForLetter(this.id)">g</div>
<div class="keyboard-button" id="key-h" onClick="checkForLetter(this.id)">h</div>
<div class="keyboard-button" id="key-i" onClick="checkForLetter(this.id)">i</div>
<div class="keyboard-button" id="key-j" onClick="checkForLetter(this.id)">j</div>
<div class="keyboard-button" id="key-k" onClick="checkForLetter(this.id)">k</div>
<div class="keyboard-button" id="key-l" onClick="checkForLetter(this.id)">l</div>
<div class="keyboard-button" id="key-m" onClick="checkForLetter(this.id)">m</div>
<div class="keyboard-button" id="key-n" onClick="checkForLetter(this.id)">n</div>
<div class="keyboard-button" id="key-o" onClick="checkForLetter(this.id)">o</div>
<div class="keyboard-button" id="key-p" onClick="checkForLetter(this.id)">p</div>
<div class="keyboard-button" id="key-q" onClick="checkForLetter(this.id)">q</div>
<div class="keyboard-button" id="key-r" onClick="checkForLetter(this.id)">r</div>
<div class="keyboard-button" id="key-s" onClick="checkForLetter(this.id)">s</div>
<div class="keyboard-button" id="key-t" onClick="checkForLetter(this.id)">t</div>
<div class="keyboard-button" id="key-u" onClick="checkForLetter(this.id)">u</div>
<div class="keyboard-button" id="key-v" onClick="checkForLetter(this.id)">v</div>
<div class="keyboard-button" id="key-x" onClick="checkForLetter(this.id)">x</div>
<div class="keyboard-button" id="key-y" onClick="checkForLetter(this.id)">y</div>
<div class="keyboard-button" id="key-z" onClick="checkForLetter(this.id)">z</div>
</div>
</div>
<script src="./js/WordGenerator.js"></script>
<script src="./js/LivesCounter.js"></script>
</body>
</html>
change this line :
censoredWord = setCharVisible(censoredWord, randomWord, i+1);
to the following line :
censoredWord = setCharVisible(censoredWord, randomWord, parseInt(i)+1);
Turns out i+1 was concatenating 1 instead of adding.
Ex: when i = 1 , i+1 was giving 11.
I have tried the solution is this post but it doesn't seem to help me. I have to store a Hex color in to a number and be able to successfully convert it back to hex color
I have put a working code below
hexToNum = () => {
const orignalColor = '#00FF7B';
const newStr = orignalColor.replace('#', '');
document.querySelector('#num').value = parseInt(newStr, 16);;
}
NumToHex = () => {
const el = document.querySelector('#str');
const num = el.value;
const str1 = num.toString(16);
console.log(str1);
el.style.borderColor = '#' + str1;
el.style.backgroundColor = '#' + str1;
}
.color1 {
border-radius: 50%;
width: 21px;
height: 21px;
border: 3px solid;
box-shadow: 0 1px 1px 0 rgba(0, 0, 0, .13);
border-color: #00FF7B;
background-color: #00FF7B;
}
.color2 {
border-radius: 50%;
width: 21px;
height: 21px;
border: 3px solid;
box-shadow: 0 1px 1px 0 rgba(0, 0, 0, .13);
}
<div class='color1'></div>
<br/>
<button onclick="hexToNum()">Get Numeric Value </button> <input type='text' id='num'>
<br/><br/><br/>
<div class='color2'></div>
<br/><br/>
<input type='text' id='str'>
<button onclick="NumToHex()">Set Color From Numeric Value </button>
As #reporter noticed earlier, input value is string.
So you have to convert it to number with parseInt or other method e.g.
const num = +el.value;
Then convert to hex and left pad the result with 0:
const str1 = num.toString(16).padStart(6, '0');
See the snippet below:
hexToNum = () => {
const orignalColor = '#00FF7B';
const newStr = orignalColor.replace('#', '');
document.querySelector('#num').value = parseInt(newStr, 16);;
}
NumToHex = () => {
const el = document.querySelector('#str');
const num = +el.value;
const str1 = num.toString(16).padStart(6, '0');
console.log(str1);
const c2 = document.querySelector('.color2')
c2.style.borderColor = '#' + str1;
c2.style.backgroundColor = '#' + str1;
}
.color1 {
border-radius: 50%;
width: 21px;
height: 21px;
border: 3px solid;
box-shadow: 0 1px 1px 0 rgba(0, 0, 0, .13);
border-color: #00FF7B;
background-color: #00FF7B;
}
.color2 {
border-radius: 50%;
width: 21px;
height: 21px;
border: 3px solid;
box-shadow: 0 1px 1px 0 rgba(0, 0, 0, .13);
}
<div class='color1'></div>
<br/>
<button onclick="hexToNum()">Get Numeric Value </button> <input type='text' id='num'>
<br/><br/><br/>
<div class='color2'></div>
<br/><br/>
<input type='text' id='str'>
<button onclick="NumToHex()">Set Color From Numeric Value </button>
Hope it helps.
Im trying to create a drop down menu when hovering, something like the the following.
Under the header of a website.
Im doing so with jQuery, Im using the events mouseEnter and mouse leave.
with the following code.
var LastThis = null;
$(".divOpener, #floatingNewNav")
.mouseleave(function(event)
{
console.log(event);
if($(event.toElement).attr("id") != "floatingNewNav") // do not close since we leaved the element but we got on the floating nav.
{
$("#floatingNewNav").hide(0);
if(LastThis.attr("id") == "ShopByBrand")
{
LastThis.removeClass("NavSelected");
$("#"+LastThis.attr("id")+"_Nav").css("display","none");
}
if(LastThis.attr("id") == "ShopByCategory")
{
LastThis.removeClass("NavSelected");
$("#"+LastThis.attr("id")+"_Nav").css("display","none");
}
if(LastThis.attr("id") == "ShopByPrice")
{
LastThis.removeClass("NavSelected");
$("#"+LastThis.attr("id")+"_Nav").css("display","none");
}
}
});
$(".divOpener")
.mouseenter(function()
{
LastThis = $(this);
if($(this).attr("id") == "ShopByBrand")
{
$("#"+$(this).attr("id")+"_Nav").css("display","block");
$(this).addClass('NavSelected');
}
if($(this).attr("id") == "ShopByCategory")
{
$("#"+$(this).attr("id")+"_Nav").css("display","block");
$(this).addClass('NavSelected');
}
if($(this).attr("id") == "ShopByPrice")
{
$("#"+$(this).attr("id")+"_Nav").css("display","block");
$(this).addClass('NavSelected');
}
var DivPosition = $(this).parent().position();
var Position = $(this).position();
var curTop = DivPosition.top;
var curLeft = Position.left;
var curWidth = $(this).width();
var curHeight = $(this).parent().height();
var DivWidth = $(this).parent().width();
var WidthOfNav = 400;
var OffSetLeft = (curLeft+(curWidth/2)-(WidthOfNav/2)+WidthOfNav)-(DivPosition.left+DivWidth);
var OffSetLeft = (OffSetLeft>0?OffSetLeft:0);
$("#floatingNewNav").css("position","absolute");
$("#floatingNewNav").css("height","100px");
$("#floatingNewNav").css("top",(curTop+curHeight)+"px");
$("#floatingNewNav").css("left",((curLeft+(curWidth/2))-(WidthOfNav/2))-OffSetLeft+"px");
$("#floatingNewNav").css("width",WidthOfNav+"px");
$("#floatingNewNav").show(0);
});
Html
<div id="newNavDiv">
<span><form style="display: inline-block;" action="search.php" method="get"><input id="SearchBar" name="q" type="text"></form></span>
<div class="SearchButtonDiv"><input id="SearchButton" type="button" value="SEARCH"></div>
<span class="NewNavSeparator"></span>
<div id="Special" style="color: red;">
SPECIALS
</div>
<span class="NewNavSeparator"></span>
<div id="ShopByBrand" class="divOpener">
SHOP BY<br/>BRAND
</div>
<span class="NewNavSeparator"></span>
<div id="ShopByCategory" class="divOpener">
SHOP BY<br/>CATEGORY
</div>
<span class="NewNavSeparator"></span>
<div id="ShopByPrice" class="divOpener">
SHOP BY<br/>PRICE
</div>
</div>
<div id="floatingNewNav">
<div id="ShopByBrand_Nav"></div>
<div id="ShopByCategory_Nav"></div>
<div id="ShopByPrice_Nav"></div>
</div>
css
#WebsiteHeader
{
height: 170px;
background: url("Photo/header.png") no-repeat top;
background-size:100%;
}
#NewNavBar
{
height: 42px;
background: url("Photo/newNavigator.png") no-repeat top;
background-size:100%;
padding: 4px;
text-align: center;
}
#newNavDiv
{
display: inline-block;
width: 960px;
text-align: right;
}
#SearchBar
{
font-size: 16px;
color: grey;
width: 245px;
height: 24px;
padding-left: 5px;
background-color: #ffffff;
border-radius: 4px 4px 4px 4px;
-moz-border-radius: 4px 4px 4px 4px;
-webkit-border-radius: 4px 4px 4px 4px;
border: 1px solid #c7c7c7;
}
.SearchButtonDiv
{
display: inline-block;
}
#SearchButton
{
color:#ffffff;
font-size: 13px;
height: 30px;
background-color: red;
padding: 8px;
border-radius: 4px 4px 4px 4px;
-moz-border-radius: 4px 4px 4px 4px;
-webkit-border-radius: 4px 4px 4px 4px;
border: 0px solid;
}
#Special
{
vertical-align: middle;
width: 130px;
display: inline-block;
text-align: center;
color: #ffffff;
font-family: "Arial";/* for firefox*/
font-family: "Arial Black";/* if browser have the font it will overide arial*/
font-weight:900;/* for firefox*/
font-size: 13px;
font-style: italic;
}
.divOpener
{
vertical-align: middle;
width: 140px;
display: inline-block;
text-align: center;
color: #ffffff;
font-family: "Arial";/* for firefox*/
font-family: "Arial Black";/* if browser have the font it will overide arial*/
font-weight:900;/* for firefox*/
font-size: 13px;
font-style: italic;
}
.NewNavSeparator
{
border-right: 1px rgba(245, 245, 245, 0.70) solid;
margin-right: 5px;
margin-left: 6px;
height: 30px;
}
#MainPagesLinks
{
padding-bottom: 0;
}
#MainPagesLinks a
{
text-align: center;
color:#ffffff;
text-decoration: none;
font-size: 13px;
width: 75px;
display: inline-block;
background-color: red;
padding-left: 4px;
padding-right: 4px;
border-radius: 4px 4px 0px 0px;
-moz-border-radius: 4px 4px 0px 0px;
-webkit-border-radius: 4px 4px 0px 0px;
border-top: 1px solid rgba(255,240,240,0.4);
border-right: 1px solid rgba(255,240,240,0.4);
border-left: 1px solid rgba(255,240,240,0.4);
box-shadow:
inset 0 3px 2px rgba(255,255,255,.22),
inset 0 20px 10px rgba(255,255,255,.12),
0 0 4px 1px rgba(0,0,0,.1),
0 3px 2px rgba(0,0,0,.2);
/*border: 1px solid #000000;*/
}
#floatingNewNav
{
background-color: #aaaac6;
margin-top: 0px;
border-radius: 0px 0px 6px 6px;
-moz-border-radius: 0px 0px 6px 6px;
-webkit-border-radius: 0px 0px 6px 6px;
}
.NavSelected
{
color:black;
background-color: #aaaac6;
border-bottom: 0px #aaaac6 solid;
border-radius: 6px 6px 0px 0px;
-moz-border-radius: 6px 6px 0px 0px;
-webkit-border-radius: 6px 6px 0px 0px;
}
.divOpener class is the <a> Shop by category</a> and others links
#floatingNewNav
Here is the live example.
https://www.newyorkpowertools.com/Template/headerTemplate.html
You will see in that example that it works in chrome,Ie,safari But on firefox it doesn't work. beacause for some reason firefox dont return the object toElement in the event object..
My question
Is there a way I could create an event mouseEnter and mouseLeave with two element and fake that it is ONLY one element so I dont need to
if($(event.toElement).attr("id") != "floatingNewNav")
Thanks for the help, And Sorry for the confusing question,.
To create a drop-down menu that appears on hover, like the one in your example, I would use CSS. See example below:
HTML
<ul id="menu">
<li>Menu 1</li>
<li>Menu 2
<ul class="sub-menu">
<li>Sub Menu 1</li>
<li>Sub Menu 2</li>
<li>Sub Menu 3</li>
<li>Sub Menu 4</li>
</ul>
</li>
<li>Menu 3</li>
</ul>
CSS
#menu li ul {
display: none;
}
#menu li:hover ul {
display: block;
}
You can simply do this http://jsfiddle.net/aheLv/1/
$(".divOpener, #floatingNewNav").mouseenter(function () {
if (!$(this).is('#floatingNewNav')) {
LastThis = $(this);
}
$("#" + LastThis.attr("id") + "_Nav").css("display", "block");
LastThis.addClass('NavSelected');
var DivPosition = LastThis.parent().position();
var Position = LastThis.position();
var curTop = DivPosition.top;
var curLeft = Position.left;
var curWidth = LastThis.width();
var curHeight = LastThis.parent().height();
var DivWidth = LastThis.parent().width();
var WidthOfNav = 400;
var OffSetLeft = (curLeft + (curWidth / 2) - (WidthOfNav / 2) + WidthOfNav) - (DivPosition.left + DivWidth);
var OffSetLeft = (OffSetLeft > 0 ? OffSetLeft : 0);
$("#floatingNewNav").css("position", "absolute");
$("#floatingNewNav").css("height", "100px");
$("#floatingNewNav").css("top", (curTop + curHeight) + "px");
$("#floatingNewNav").css("left", ((curLeft + (curWidth / 2)) - (WidthOfNav / 2)) - OffSetLeft + "px");
$("#floatingNewNav").css("width", WidthOfNav + "px");
$("#floatingNewNav").show(0);
});
There are lot of things you can do to refactor this code. Actually there are some extra stuff in the fiddle that I am taking them out now, I will update soon
UPDATE:
here is the final code
var LastThis = null;
var openers = $(".divOpener, #floatingNewNav");
openers.mouseleave(function (event) {
$("#floatingNewNav").hide();
LastThis.removeClass("NavSelected");
$("#" + LastThis.attr("id") + "_Nav").hide();
});
openers.mouseenter(function () {
if (!$(this).is('#floatingNewNav')) {
LastThis = $(this);
}
$("#" + LastThis.attr("id") + "_Nav").show();
LastThis.addClass('NavSelected');
var DivPosition = LastThis.parent().position();
var Position = LastThis.position();
var curTop = DivPosition.top;
var curLeft = Position.left;
var curWidth = LastThis.width();
var curHeight = LastThis.parent().height();
var DivWidth = LastThis.parent().width();
var WidthOfNav = 400;
var OffSetLeft = (curLeft + (curWidth / 2) - (WidthOfNav / 2) + WidthOfNav) - (DivPosition.left + DivWidth);
var OffSetLeft = (OffSetLeft > 0 ? OffSetLeft : 0);
$("#floatingNewNav").css({
'position': 'absolute',
'height': '100px',
'top': (curTop + curHeight) + 'px',
'left': ((curLeft + (curWidth / 2)) - (WidthOfNav / 2)) - OffSetLeft + 'px',
'width': WidthOfNav + 'px'
}).show();
});
http://jsfiddle.net/aheLv/2/
As a suggestion, menus like these can be done in css only if you structure your html the right way. See Kevin's answer for the structure
Just to throw out a different concept, your picture screams "jQuery tabs" :-), so I used simple tabs, and created a jQuery trigger event for each one.
FIDDLE
JS
$('.charts').tabs();
$('#firstone').mouseover(function(){
$(this).trigger('click');
});
$('#secondone').mouseover(function(){
$(this).trigger('click');
});
$('#thirdone').mouseover(function(){
$(this).trigger('click');
});
Not elegant, but I'll play with it some more and see if it can be 'elegantized'.
Seems like you're overcomplicating things..
How about just tracking the direction of the mouse, and if its headed downward, don't hide the menuitems below..
Check this fiddle..
http://jsfiddle.net/ReVLN/2/
Checked its working in Mozilla and chrome/etc..
var mY = 0;
$('div.menuItems').mousemove(function(e){
// moving upward
if (e.pageY < mY) {
flag = "upward";
} else {
flag = "downward";
}
// set new mY after doing test above
mY = e.pageY;
});
Thanks,
jf_it
I know CSS is "cascading", but in this case I want the effect to ascend. I'm open for either a JS or CSS solution, but honestly I'd prefer the solution with the least amount of code or overhead.
When I hover over a (child) letter, I want the entire background color to change for the ENTIRE WINDOW, not just the child element. Each letter is contained within the parent #word div which fills the whole window (or body).
It would be nice if something like the below existed in css:
#h:hover #word{
background-color: rgba(0, 102, 0, .5);
}
But it's not working. Anyone have any ideas??
HTML:
<div id="word">
<h1><a id="h" class= "letter" href=#>H</a></h1>
<h1><a class= "letter" href=#>E</a></h1>
<h1><a class= "letter" href=#>L</a></h1>
<h1><a class= "letter" href=#>L</a></h1>
<h1><a class= "letter" href=#>O</a></h1>
</div>
CSS:
body {
/*font-family: 'Sigmar One', cursive;*/
font-family: 'Chango', cursive;
font-size: 115px;
color: white;
text-shadow: 5px 5px 5px #000;
/* background-color: #0047b2 */
width: 100%;
height: 100%;
margin: 0px;
background: url(img/texture.png) repeat;
}
#word {
position:absolute;
height:100%;
width: 70%;
display: table;
padding: 0 15% 0 15%;
background: rgba(0, 71, 178, .5);
}
h1 {
display: table-cell;
vertical-align: middle;
text-align:center;
height: 1em;
}
a {
/*border: 1px solid black;*/
display: inline-block;
line-height: 100%;
overflow: hidden;
}
a:visited, a:active {
text-decoration: none;
color: white;
/*color: #E8E8E8;*/
}
a:link {
text-decoration: none;
color: white;
text-shadow: 3px -3px 0px black, -2px 2px 5px #0056b2;
}
a:hover {
text-shadow: 5px 5px 5px #000;
color: white;
}
#h:hover #word{
background-color: rgba(0, 102, 0, .5);
}
#media (max-width: 1330px){
#word {
width: 100%;
padding: 0px;
}
}
Fiddle: http://jsfiddle.net/SZ9ku/1/
The solution would probably be JS:
$(".letter").hover(function() {
$(this).closest("#word").toggleClass("hovered")
});
Here is a fiddle: http://jsfiddle.net/zT9AS/2
True;
#word #h:hover {
background-color: rgba(0, 102, 0, .5);
}
False;
#h:hover #word{
background-color: rgba(0, 102, 0, .5);
}
A without jquery solution:
onload = function()
{
var links = document.getElementsByTagName('a');
for (var i = 0; i < links.length; ++i)
{
if (links[i].className == 'letter')
{
links[i].onmouseover = function() {
document.getElementById('word').style.backgroundColor="#0000FF";
};
links[i].onmouseout = function() {
document.getElementById('word').style.backgroundColor="#FFFFFF";
};
}
}
}
It can be done in pure JS, no jQuery (I assume you don't want that since it wouldn't be that light in code), this is the best I could came out with:
var word = document.getElementsByClassName("letter");
for (i=0; i<word.length; i++) {
word[i].addEventListener("mouseenter", function( event ) {
parent = event.target.parentNode.parentNode;
//whenever the mouse hovers over a letter this will be evaluated once
parent.style.backgroundColor = "green";
});
word[i].addEventListener("mouseout", function( event ) {
parent = event.target.parentNode.parentNode;
//whenever the mouse hovers over a letter this will be evaluated once
parent.style.backgroundColor = "";
});
}
Try it in this fiddle: http://jsfiddle.net/SZ9ku/17/
In POJS, add the following
CSS
.wordBg {
background: rgba(0, 102, 0, .5) !important;
}
Javascript
var changeWordBg = (function (word) {
return function (evt) {
if (evt.target.classList.contains("letter")) {
switch (evt.type) {
case "mouseover":
word.classList.add("wordBg");
break;
case "mouseout":
word.classList.remove("wordBg");
break;
default:
}
}
};
}(document.getElementById("word")));
document.body.addEventListener("mouseover", changeWordBg, false);
document.body.addEventListener("mouseout", changeWordBg, false);
On jsfiddle