I'm trying to create a subwindow where users can see lists they make, unfortunately the list elements aren't being stylized and I'm at a loss as to why that's the case. I create the window as follows: windowName.document.body.innerHTML = '<html> <head> <link rel="stylesheet" type="text/css" href="list.css"> </head> <ul id = "searchSuggestions"> </ul></html>'. I create the list items in javascript using:
let a = windowName.document.createElement("a");
a.textContent=movieTitle
a.setAttribute('href','#');
let listItem = windowName.document.createElement("li")
listItem.appendChild(a)
suggestionList.appendChild(listItem);
The problem is that when these elements show up on the page they don't follow any of the formatting in the "list.css" file.
Here is the list CSS file I'm trying to use:
#searchSuggestions {
/* Remove default list styling */
list-style-type: none;
padding: 0;
margin: 0;
}
#searchSuggestions li a {
border: 1px solid #ddd; /* Add a border to all links */
margin-top: -1px; /* Prevent double borders */
background-color: #f6f6f6; /* Grey background color */
padding: 12px; /* Add some padding */
text-decoration: none; /* Remove default text underline */
font-size: 18px; /* Increase the font-size */
color: black; /* Add a black text color */
display: block; /* Make it into a block element to fill the whole list */
}
#searchSuggestions li a:hover:not(.header) {
background-color: #eee; /* Add a hover effect to all links, except for headers */
}
The final HTML of the window (using f12) is as follows:
<html>
<head><link rel="stylesheet" type="text/css" href="list.css"></head>
<body>
<div style="text-align: center;">
<h1 id="listTitle">new</h1>
<input id="searchBar" type="text" placeholder="Search..">
<button id="addBtn">Add</button>
<ul id="searchSuggestions">
<li>Toy Story</li>
<li>Toy Story 4</li>
<li>Toy Story 2</li>
</ul>
</div>
</body>
</html>
My question is how do I make it so that my listItems are stylized?
Update: After a couple more hours of trial and error I finally got a useful error message from google chrome when I tried to load the css file referring to it as "file:///{directory for css file}" chrome console told me that it "wasn't allowed to load local resources". With this new found information I uploaded my CSS to a webserver and referred to the URL that the CSS file is located and now my window has CSS.
Related
I have a problem when I'm trying to load another HTML file into my existing one. I am doing that with JavaScript with this fuction inside my html code
<script>
function load_home(){
document.getElementById("content").innerHTML='<object type="type/html" data="New folder\home.html" ></object>';
}
</script>
Q1: This code does not find the "home.html" when it is in the folder if I move it to the same folder and change it to
data="home.html" it works as it should . Can it be solved ?
Q2: Even when the code finds my "home.html" it loads in a box-type thing with scroll bars , to be able to see the full
content of the page ( the scroll bars can be vertical or horizontal depending on the content inside the loaded page )
The "index.html" and it's "style.css" file :
/* Font to left and change text type*/
body{
margin : 0;
padding : 0;
font-family : 'Arial',serif;
min-width:1200px;
}
a{
text-decoration : none;
}
/*NAV CLASS */
#menu >.nav {
background-color : #87CEEB;
color: white;
list-style : none;
padding : 4px 0 12px 0;
margin : 0px;
}
/*CONTENTS RIGHT*/
.nav > .nav-contects{
text-align : right;
}
#menu >.nav > .nav-contects > li {
display : inline-block;
padding-right: 50px;/*same as 0 25px 0 25px ( top left bottom right */
font-size: 16px;
margin : 0;
position : relative;
bottom : 10px; /*align width center */
}
/*a tag inside a li tag inside a .nav class*/
#menu >.nav > .nav-contects > li > a {
color: #f79963;
}
/* a tag inside a li tag inside a .nav class while mouse hovering */
#menu > .nav > .nav-contects > li > a:hover {
color : #ffffff;
padding : 0 0 0 0 ;
/*margin : 0px;
background-color : #888888;*/
}
<DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>
my title
</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body onload="load_home()">
<nav id="menu">
<ul class="nav">
<div class="nav-contects">
<li>Home</li>
</div>
</ul>
</nav>
<div id="content" align = "center">
</div>
<script>
function load_home(){
document.getElementById("content").innerHTML='<object type="type/html" data="New folder\home.html" ></object>';
}
</script>
<div class="footer" align = "center">
<p align = "center"> <i>an awesome business</i> </p>
</div>
</body>
</html>
the "home.html" file
<DOCTYPE html>
<html lang="en">
<body>
Some random long text
dasfda gsdwgdsgd
sgsdgsdgdsf sadddad asddddddddddddddddddddddddddddddddddddddddddddddd
</body>
</html>
PS : this may be all wrong , maybe I'm trying to do everything using the wrong way
PSS : this is not the full code of my documents , I removed a lot of my code to be sure that there were no bug with it , including style and other
EDIT#1: I want the "restricted" box to disappear and open the "home.html" like it should if I open it from my computer directly"
I really appreciate any help you can provide.
(1) This issue is likely caused by the space in your url. It should be escaped using encodeURI(src) or src.replace(/ /g, '%20')
CSS and JQuery: spaces inside image name break code of url()
(2) If you would simply like the scrollbars to disappear, add the style overflow: hidden to your popup. Be warned however that if any content spills out of the box it will not be visible/salvageable.
I have a page that initially displays the contents of the first div on the page,
based on an internal style sheet. Based on the menu choice it successfully
displays the chosen div and hides the others using a function called foo.
Each div has links to external pages. The problem I'm having is that when the
user selects a link and then hits the back arrow my page displays the first
div on the page and shows the previous option on the menu. I would like it to
display the div shown in the menu. I hope this makes sense.
Attached is my code and the external style sheet the page uses.
<!DOCTYPE HTML>
<html><!-- InstanceBegin template="/Templates/Ricks Universe.dwt" codeOutsideHTMLIsLocked="false" -->
<head>
<!-- InstanceBeginEditable name="doctitle" -->
<title>Fun and Games</title>
<!-- InstanceEndEditable -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width initial-scale 1.0 minimum-scale 1.0" />
<link rel="stylesheet" href="ricks.css" type="text/css" media="screen" title="Ricks Style Sheet"/>
<link rel="stylesheet" href="hh.css" type="text/css" media="handheld"/>
<link rel="stylesheet" media="print" type="text/css" href="print.css" />
<!-- InstanceBeginEditable name="head" -->
<style type="text/css">
#Games{display:inline;}
#Humor{display:none;}
</style>
<script type="text/javascript">
function foo(option)
{
var n = option.search(".HTM"); // Check for external file to link to;
if (n > -1) // If true...
{
window.location.href=option;
}
for (i in divs) //loop thru divs table
{
x=divs[i].substr(1) //Get value for option without #
z=document.getElementById(x) // Locate div
if (option == divs[i]) //On match to table...
{
z.style.display= "inline" //Display div on page
} else
{
z.style.display="none" //On no match hide div on page
}
}
}
</script>
<!-- InstanceEndEditable -->
<!-- InstanceParam name="home" type="boolean" value="false" -->
<script type="text/javascript">
function displaymenu() {
document.getElementById("content").style.display="none";
document.getElementById("header").style.display="none";
document.getElementById("footer").style.display="none";
document.getElementById("menu").style.display ='inline';
document.getElementById("menu").style.width="100%";
document.getElementById("menu").style["text-align"]='center';
document.getElementById("menu").style.height="300%";
document.getElementById("menu").style.zoom="300%";
};
</script>
<style type="text/css">
<!--
-->#media only screen
and (max-device-width : 667px)
and (orientation : portrait)
and (-webkit-min-device-pixel-ratio : 2)
{
.sidebar1 {display:none;}
.header {display:none;}
.footer {display: none;}
.pagepics {display:none;}
.menulink {display:inline;}
.content {height:100%;
width:100%;}
.textSmall{
font-size:x-large;
font-weight:bold;
}
#titlex {display:inline;}
.bigpic {
width:400;
margin-left:0px;
}
</style><!--[if lte IE 7]>
<style>
.content { margin-right: -1px; } /* this 1px negative margin can be placed on any of the columns in this layout with the same corrective effect. */
ul.nav a { zoom: 1; } /* the zoom property gives IE the hasLayout trigger it needs to correct extra whiltespace between the links */
</style>
<![endif]--></head>
<body>
<!-- InstanceBeginEditable name="onload" -->
<script type="text/javascript">
var string ="#Games,#Humor"; //Load table for foo to match against
var divs = new Array();
divs = string.split(",");
var opt = document.getElementById("StoreDirectory").selected,value; // Determine current selected value;
foo("opt"); //Display selected section and hide other;
</script>
<!-- InstanceEndEditable -->
<div class="container" id="wrapper">
<div class="header" id="header">
<p class="clock">
<iframe src="http://free.timeanddate.com/clock/i425m2zy/n179/tct/pct/ahl/avt/tt0/ta1" frameborder="0" width="378" height="19" allowTransparency="true"></iframe></p><br/><br/>
<!-- InstanceBeginEditable name="title" -->
<p class="title">Fun and Games</p>
<!-- InstanceEndEditable -->
<!-- end .header --></div>
<div class="sidebar1" id="menu">
<ul class="nav">
<li>Meet the dogs</li>
<li>Rick's Dog Page</li>
<li>Art</li>
<li>Automotive</li>
<li>Babies</li>
<li>The Boutique</li>
<li>Catalogs</li>
<li>Charities</li>
<li>Computing</li>
<li>Day Care</li>
<li>Department Stores</li>
<li>Dogs In Competition</li>
<li>Drug Stores</li>
<li>Education</li>
<li>Electronics</li>
<li>Employment</li>
<li>Entertainment</li>
<li>Financial</li>
<li>Fitness</li>
<li>Flowers</li>
<li>Food</li>
<li>Fun and Games</li>
<li>Gardening</li>
<li>Government</li>
<li>Greeting Cards</li>
<li>Groceries</li>
<li>Health</li>
<li>Hobbies</li>
<li>Home Improvement</li>
<li>Information</li>
<li>Internet and More</li>
<li>Jewelry</li>
<li>Literature</li>
<li>Maps and Directions</li>
<li>Music and Video</li>
<li>Movies</li>
<li>News Stand</li>
<li>Office Supplies</li>
<li>People</li>
<li>Pets</li>
<li>Phones</li>
<li>Photography</li>
<li>Post Office</li>
<li>Price Comparison</li>
<li>Real Estate</li>
<li>Security</li>
<li>Searches</li>
<li>Senior Page</li>
<li>Shoe Store</li>
<li>Shopping Clubs</li>
<li>Sports</li>
<li>Toys and Games</li>
<li>Television</li>
<li>Travel</li>
</ul>
<!-- end .sidebar1 --></div>
<div class="content" id="content">
<p class="menulink" > <a onclick="displaymenu()" href="javascript:void(0);" >
<span>Menu</span></a></p>
<script type="text/javascript">
var head = '<br/><br/><h3 id = "titlex">';
var title=document.title;
var trail = '</h3>'
var heading = head + title + trail;
document.write(heading);
</script>
<!-- InstanceBeginEditable name="content" -->
<p><img class="pagepics" style="width:250px;"src="Pictures/weimball.jpg" alt="weimball.jpg" /></p>
<div id="form" class="form">
<form action="">
<h5>Page Directory</h5>
<select id="StoreDirectory" name="StoreDirectory" onchange="foo(this.value)">
<option value="#Games">Games</option>
<option value="#Humor">Humor</option>
</select>
</form>
</div>
<div class="d1">
<div <a id="Games" name="Games"></a>
<h2>Games</h2>
<ul>
<li>Addicting Games</li>
<li>BestCrosswords.com</li>
<li>The Bingo Zone</li>
<li>blufrA trivia game challenging you to identify statements as true or false</li>
<li>Free Flash Online Games</li>
<li>FreeArcade.com</li>
<li>Gamespot</li>
<li> It's Your TurnChess, Checkers, Backgammon and more</li>
<li>Ultimate Online Gaming</li>
<li>JigZoneJigsaw Puzzle Paradise</li>
<li>Play-Free-Online-Games.netMulti Player Games on the Internet</li>
<li>Puzzle Choice</li>
<li>The Puzzle Connection</li>
<li>Web Sudoku</li>
</ul>
</div>
<div <a id="Humor" name="Humor"></a>
<h2>Humor</h2>
<ul>
<li>BreakFunny Pics, Hot Chicks, and Cool Flicks</li>
<li>Dumb Criminal Acts!</li>
<li>The Darwin AwardsImprovement of the human genome by honoring those who accidentally kill themselves in really stupid ways</li>
<li>The Pay BackGet revenge with this collection of revenge ideas, pranks, and practical jokes</li>
<li>Practical Jokes</li>
</ul>
</div>
</div>
<!-- InstanceEndEditable -->
<!-- end .content --></div>
<div class="footer" id="footer">
<a class="sitemap" href="SiteMap.htm">Site map</a> ¦ <a href="index.html"> Home</a >
<!-- end .footer --></div>
<!-- end .container --></div>
Style sheet
body {
font: 100%/1.4 Verdana, Arial, Helvetica, sans-serif;
background: #4E5869;
margin: 0;
padding: 0;
color: #000;
}
/* ~~ Element/tag selectors ~~ */
ul, ol, dl { /* Due to variations between browsers, it's best practices to zero padding and margin on lists. For consistency, you can either specify the amounts you want here, or on the list items (LI, DT, DD) they contain. Remember that what you do here will cascade to the .nav list unless you write a more specific selector. */
padding: 0;
margin: 0;
}
h1, h2, h3, h4, h5, h6, p {
margin-top: 0; /* removing the top margin gets around an issue where margins can escape from their containing div. The remaining bottom margin will hold it away from any elements that follow. */
padding-right: 15px;
padding-left: 15px; /* adding the padding to the sides of the elements within the divs, instead of the divs themselves, gets rid of any box model math. A nested div with side padding can also be used as an alternate method. */
}
a img { /* this selector removes the default blue border displayed in some browsers around an image when it is surrounded by a link */
border: none;
}
/* ~~ Styling for your site's links must remain in this order - including the group of selectors that create the hover effect. ~~ */
a:link {
color:#00000;
text-decoration: underline; /* unless you style your links to look extremely unique, it's best to provide underlines for quick visual identification */
}
a:visited {
color: #000000;
text-decoration: underline;
}
/* ~~ this container surrounds all other divs giving them their percentage-based width ~~ */
.container {
border:solid;
border-width:10px;
border-color:#008800;
width: 80%;
max-width: 1260px;/* a max-width may be desirable to keep this layout from getting too wide on a large monitor. This keeps line length more readable. IE6 does not respect this declaration. */
min-width: 780px;/* a min-width may be desirable to keep this layout from getting too narrow. This keeps line length more readable in the side columns. IE6 does not respect this declaration. */
background: #FFF;
margin: 0 auto; /* the auto value on the sides, coupled with the width, centers the layout. It is not needed if you set the .container's width to 100%. */
overflow:visible;
}
/* ~~ the header is not given a width. It will extend the full width of your layout. It contains an image placeholder that should be replaced with your own linked logo ~~ */
.header {
background: #227Dff;
margin-bottom:-20px;
height:150px;
}
/* ~~ These are the columns for the layout. ~~
1) Padding is only placed on the top and/or bottom of the divs. The elements within these divs have padding on their sides. This saves you from any "box model math". Keep in mind, if you add any side padding or border to the div itself, it will be added to the width you define to create the *total* width. You may also choose to remove the padding on the element in the div and place a second div within it with no width and the padding necessary for your design.
2) No margin has been given to the columns since they are all floated. If you must add margin, avoid placing it on the side you're floating toward (for example: a right margin on a div set to float right). Many times, padding can be used instead. For divs where this rule must be broken, you should add a "display:inline" declaration to the div's rule to tame a bug where some versions of Internet Explorer double the margin.
3) Since classes can be used multiple times in a document (and an element can also have multiple classes applied), the columns have been assigned class names instead of IDs. For example, two sidebar divs could be stacked if necessary. These can very easily be changed to IDs if that's your preference, as long as you'll only be using them once per document.
4) If you prefer your nav on the right instead of the left, simply float these columns the opposite direction (all right instead of all left) and they'll render in reverse order. There's no need to move the divs around in the HTML source.
*/
.sidebar1 {
float: left;
width: 20%;
background: #93A5C4;
padding-bottom: 10px;
height:600px;
display:block;
overflow:auto;
margin-bottom: -10px;
}
.content {
padding: 10px 0;
width: 80%;
float: left;
height:600px;
overflow:auto;
background-color:#00aaFF;
}
/* ~~ This grouped selector gives the lists in the .content area space ~~ */
.content ul, .content ol {
padding: 0 15px 15px 40px; /* this padding mirrors the right padding in the headings and paragraph rule above. Padding was placed on the bottom for space between other elements on the lists and on the left to create the indention. These may be adjusted as you wish. */
}
/* ~~ The navigation list styles (can be removed if you choose to use a premade flyout menu like Spry) ~~ */
ul.nav {
list-style: none; /* this removes the list marker */
border-top: 1px solid #666; /* this creates the top border for the links - all others are placed using a bottom border on the LI */
margin-bottom: 15px; /* this creates the space between the navigation on the content below */
}
ul.nav li {
border-bottom: 2px inset #666; /* this creates the button separation */
}
ul.nav a, ul.nav a:visited { /* grouping these selectors makes sure that your links retain their button look even after being visited */
padding: 5px 5px 5px 15px;
display: block; /* this gives the link block properties causing it to fill the whole LI containing it. This causes the entire area to react to a mouse click. */
text-decoration: none;
background: #00A;
color: #FFF;
}
ul.nav a:hover, ul.nav a:active, ul.nav a:focus { /* this changes the background and text color for both mouse and keyboard navigators */
background: #008800;
color: #FFF;
}
/* ~~ The footer ~~ */
.footer {
padding: 10px 0;
background: #6F7D94;
position: relative;/* this gives IE6 hasLayout to properly clear */
clear: both; /* this clear property forces the .container to understand where the columns end and contain them */
text-align:center;
color: #fff;
font-size:xx-small;
}
/* ~~ miscellaneous float/clear classes ~~ */
.fltrt { /* this class can be used to float an element right in your page. The floated element must precede the element it should be next to on the page. */
float: right;
margin-left: 8px;
}
.fltlft { /* this class can be used to float an element left in your page. The floated element must precede the element it should be next to on the page. */
float: left;
margin-right: 8px;
}
.clearfloat { /* this class can be placed on a <br /> or empty div as the final element following the last floated div (within the #container) if the #footer is removed or taken out of the #container */
clear:both;
height:0;
font-size: 1px;
line-height: 0px;
}
.title {
position: relative; top: -25pt;
text-align: center;
color: #00000;
font-size:48px;
font-weight:bold;
font-family:"Times New Roman",Georgia,Serif;
padding-bottom::10px;
clear:both;
}
p.a8 {
float:right;
padding-right: 10px;
}
#weather {
margin:20px;
float: right;
}
#google {
padding-bottom: 20px;
text-align=center;
clear;
}
td {text-align:center;}
#mapq {
padding-top: 50px;
padding-bottom: 30px;
clear;
float:left;
text-align:center;
}
#ring {
text-align: center;
}
.AllDogs {
text-align: center;
}
#center {
clear;
padding-left: 50px;
padding-bottom: 30px;
text-align: center;
}
.center {
clear;
padding-left: 50px;
padding-bottom: 30px;
text-align: center;
}
p img {float:right;}
div img {float:right;}
.iconimg {
height:50px;
width:50px;
}
.form {text-align:center};
}
.form h5 {
text-align:center;
font-size:large;
}
ul li a {color:#000;}
.textSmall{font-size:small; color:#000;}
.c20 li a{color:#000;}
div p a {color:#000; font-size:small;}
.links{padding-left:60px;}
ul {list-style-image:url(Pictures/bullet-green.png); }
li a {padding-right: 10px; font-weight:bold;}
h2 {color:#0000a2;}
.menulink {display:none;}
.menulink span {
font-size:xx-large;
color:#000;
font-weight:bold;
}
#titlex {display:none;}
table {
table-layout:fixed;
}
td {
width:193px;
vertical-align:top;
text-align:center;
padding: 10px;
cellpadding: 50px;
}
td a img{
border:0px;
width:75px;
height:50px;
}
.clock {
float:left;
color: #fff;
}
.sitemap {
color:#fff;
}
.pagepics{
display:inline;
margin-right:10px;}
.icontext {
padding-left:140px;
vertical-align:top;
padding-top:0px;
margin-top:0px;
}
.pic {width:200px;
border:10px;
}
.bigpic {
float:left;
padding:0px;
width:600px;
margin-left:150px;
border: 1 solid black;
}
#pix {margin-left:100px;}
To do this you will need to have it remember what the user selected. One way to do this is to use cookies.
Here's a couple javascript functions I use to work with cookies.
function createCookie(name, value, days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
} else {
expires = "";
}
document.cookie = escape(name) + "=" + escape(value) + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = escape(name) + "=";
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i];
while (cookie.charAt(0) === ' ')
cookie = cookie.substring(1, cookie.length);
if (cookie.indexOf(nameEQ) === 0)
return unescape(cookie.substring(nameEQ.length, cookie.length));
}
return null;
}
In your foo() function call createCookie() to save the selected option. Then add a function handle the page load event. In that, call readCookie() to get the selected option to determine which div to show.
My Bad! I only somehow deleted the most important line in the script:
z.style.display= "inline"
Thank you again for your help.
I'm trying to create a menu where the currently selected (clicked) element has a different background color than the other elements (I'm trying to achieve this using JavaScript). I also use the CSS :hover pseudoclass to make the hovered element stand out by highlighting it. However, I have encountered a strange problem: when I set the background color of any element with JavaScript, its CSS hover behavior no longer works. That is, I can't highlight the element by hovering it anymore. I have checked that in Firefox and Chromium. This is the case for both jQuery and plain JavaScript.
The code is below. I have simplified it a lot to narrow down the problem. First try hovering any of the menu items, then click the "Set background color" link and hover one of the menu elements again. What I expect is the element getting red (#f00) when hovered, regardless of whether the "Set background color" button was clicked or not. For jsfiddle links, go to the bottom.
Vanilla JavaScript:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style>
p#links a {
display: inline-block;
width: 80px;
height: 22px;
line-height: 22px;
background-color: #00f;
color: #fff;
text-decoration: none;
text-align: center;
font-family: sans-serif;
}
p#links a:hover {
background-color: #f00;
}
</style>
<title>Background color</title>
</head>
<body>
<p id="links">
Link 1
Link 2
Link 3
Link 4
</p>
Set background color
<script>
document.getElementById('setbgcolor').onclick = function() {
var p = document.getElementById('links');
var elements = p.getElementsByTagName('a');
for (var i = 0; i < elements.length; i++)
elements[i].style.backgroundColor = '#ff0';
};
</script>
</body>
</html>
jQuery:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="jquery-1.11.0.js"></script>
<style>
p#links a {
display: inline-block;
width: 80px;
height: 22px;
line-height: 22px;
background-color: #00f;
color: #fff;
text-decoration: none;
text-align: center;
font-family: sans-serif;
}
p#links a:hover {
background-color: #f00;
}
</style>
<title>Background color</title>
</head>
<body>
<p id="links">
Link 1
Link 2
Link 3
Link 4
</p>
Set background color
<script>
$('a#setbgcolor').click(function() {
$('p#links a').css('background-color', '#ff0');
});
</script>
</body>
</html>
And here are jsfiddle.net links for the purpose of convenience:
Pure JavaScript: http://jsfiddle.net/5yQFM/1/
jQuery: http://jsfiddle.net/5yQFM/
The jQuery css() method maps onto the style property which maps onto the style attribute.
Rules inside a style attribute are more specific then rules in a stylesheet, so will always come after them in the cascade.
Instead of altering the CSS on the element directly, alter it by changing the classes the element belongs to and having a pre-prepared stylesheet.
you need to use !important on hover, basically it will increase its priority.
Try this,
p#links a:hover {
background-color: #f00 !important;
}
DEMO
As Quentin said it looks like a dirty one, so in that situation we can make use of the class priority concepts.
HTML:
<a class='normal' href="#">Link 1</a>
<a class='normal' href="#">Link 1</a>
CSS:
.normal { background-color: blue; }
.abnormal{ background-color: yellow; }
.normal:hover { background-color: #f00; }
JS:
$('p#links a').attr('class', 'abnormal normal');
DEMO Non-Dirty one
How about keeping the style in CSS and not in Javascript, by adding classes ?
so the line :
elements[i].style.backgroundColor = '#ff0';
Change to
elements[i].className = 'myClassForBackgrounds';
or in the jQ version
$('p#links a').css('background-color', '#ff0');
to :
$('p#links a').addClass('myClassForBackgrounds');
That way you can set your :hover as you would normally
#links a:hover, .myClassForBackgrounds:hover { background-color:#ff0; }
Just for a more simple answer, in able to just re-enable css rules just have it toggle between the color and "", so
document.getElementById("id").style.backgroundColor = "rgb(255, 125, 15)";
would be if the element wasn't already colored via javascript.
Now, if your element was already colored the code would look like this:
document.getElementById("id").style.backgroundColor = "";
That re-enables CSS so then your selectors will work.
I encountered the same problem and solved it by doing this:
I set a onmouseover event to change the background color to what the hover color is.
I set a onmouseout event to change the background color to the default color.
This way I have set a hover event with pure javascript
I have a top nav links that drive links in the left nav. The top nav contains a bunch of topics. Each topic link when clicked populates left nav with related links on the topic. So when a topic on the top nav is clicked i want it to change its color to like red while the rest are blue, but as soon as another title is clicked, i want the previously clicked link to restore its color back to blue and the newly clicked one to gain the red color. How can we do this in jquery? Adding classes and removing classes and using css is not working.. please help..
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>MY C# Notes</title>
<style type="text/css">
body,
html {margin:0; padding:0;color:#000;background:#a7a09a;}
#wrap {width:1050px;margin:0 auto;background:#99c;}
#header {padding:5px 10px;background:#ddd;}
h1 {margin:0;}
#nav {padding:5px 10px;background:#c99;}
#nav ul {margin:0;padding:0;list-style:none;}
#nav li {display:inline;margin:0;padding-right:15px;}
#main { float:right;width:780px;padding:10px;background:#9c9;min-height:600px;}
h2 {margin:0 0 1em;}
#sidebar {float:left;width:230px;padding:10px;background:#99c;min-height:600px;}
#footer {clear:both;padding:5px 10px;background:#cc9;}
#footer p { margin:0; }
* html #footer {height:1px;}
.high{color:red}
a.loader { color: blue; }
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function() {
$('a.loader').on('click', function(e) {
e.preventDefault();
$('#sidebar').load($(this).attr('href'));
$("a.loader").removeClass("high");
$(this).addClass("high");});
});
</script>
<div id="wrap">
<div id="header"><h1>My C# Notes and Exercises</h1></div>
<div id="nav">
<ul>
<li><a class="loader" href="topic1.html">Topic1</a></li>
<li><a class="loader" href="topic2.html">Topic2</a></li>
<li><a class="loader" href="topic3.html">Topic3</a></li>
<li><a class="loader" href="topic4.html">Topic4</a></li>
<li>LocalBrowser</li>
</ul>
</div>
<div id="main">
</div>
<div id="sidebar"></div>
<div id="footer">
<p>C# Online Tutorials</p>
</div>
</div>
</body>
</html>
Your css class .loader is getting priority over .high; you can fix this by:
-adding !important to the declaration for .high: .high {color: red !important;}
-swapping the order of the declarations in your css: a.loader { color: blue;} a.high { color: red; }
-or removing .loader when you add .high:
$(document).ready(function() {
$('a.loader').on('click', function(e) {
e.preventDefault();
$('#sidebar').load($(this).attr('href'));
$("a.high").not(this).removeClass("high").addClass('loader');
$(this).removeClass('loader').addClass("high");
});
});
The blue from the loader class is overwriting the red so use this:
.high{color:red !important}
http://jsfiddle.net/AZqUx/
Currently, you have two relevant CSS rules here:
a.loader { color: blue; }
.high { color: red; }
One of the most important principals of CSS is that more specific rules will override less specific ones. Of the above 2 rules, the first applies to all <a> elements with class loader, and the second applies to all elements with class high. Since the first is more specific (includes a tag as well as class description), it is given priority and overrides the color: red; from the other rule. The easiest way to be fix this would be to make your second rule more specific:
a.loader { color: blue; }
a.high { color: red; }
Since the rule for a.high is declared later, it will be given priority. However, you can future-proof this a bit better by actually making the second rule more specific than the first. Assuming you only need this to work in child elements of the <div id="nav"> element, you can do this:
a.loader { color: blue; }
#nav a.high { color: red; }
This you can move both declarations around freely and not get any unexpected behavioral change. You find the CSS specificity rules helpful if you have any questions about why this works. :D
I’m trying to prevent the browser from using the :hover effect of the CSS, via JavaScript.
I have set the a and a:hover styles in my CSS, because I want a hover effect, if JS isn’t available. But if JS is available, I want to overwrite my CSS hover effect with a smoother one (using the jQuery color plugin for example.)
I tried this:
$("ul#mainFilter a").hover(
function(e){ e.preventDefault(); ...do my stuff... },
function(e){ e.preventDefault(); ...do my stuff... });
I also tried it with return false;, but it does not work.
Here is an example of my problem: http://jsfiddle.net/4rEzz/. The link should just fade without getting gray.
As mentioned by fudgey, a workaround would be to reset the hover styles using .css() but I would have to overwrite every single property, specified in the CSS (see here: http://jsfiddle.net/raPeX/1/ ). I am looking for a generic solution.
Does anyone know how to do this?
PS: I do not want to overwrite every style i have set for the hover.
There isn’t a pure JavaScript generic solution, I’m afraid. JavaScript isn’t able to turn off the CSS :hover state itself.
You could try the following alternative workaround though. If you don’t mind mucking about in your HTML and CSS a little bit, it saves you having to reset every CSS property manually via JavaScript.
HTML
<body class="nojQuery">
CSS
/* Limit the hover styles in your CSS so that they only apply when the nojQuery
class is present */
body.nojQuery ul#mainFilter a:hover {
/* CSS-only hover styles go here */
}
JavaScript
// When jQuery kicks in, remove the nojQuery class from the <body> element, thus
// making the CSS hover styles disappear.
$(function(){}
$('body').removeClass('nojQuery');
)
Use a second class that has only the hover assigned:
HTML
<a class="myclass myclass_hover" href="#">My anchor</a>
CSS
.myclass {
/* all anchor styles */
}
.myclass_hover:hover {
/* example color */
color:#00A;
}
Now you can use Jquery to remove the class, for instance if the element has been clicked:
JQUERY
$('.myclass').click( function(e) {
e.preventDefault();
$(this).removeClass('myclass_hover');
});
Hope this answer is helpful.
You can manipulate the stylesheets and stylesheet rules themselves with javascript
var sheetCount = document.styleSheets.length;
var lastSheet = document.styleSheets[sheetCount-1];
var ruleCount;
if (lastSheet.cssRules) { // Firefox uses 'cssRules'
ruleCount = lastSheet.cssRules.length;
}
else if (lastSheet.rules) { / /IE uses 'rules'
ruleCount = lastSheet.rules.length;
}
var newRule = "a:hover { text-decoration: none !important; color: #000 !important; }";
// insert as the last rule in the last sheet so it
// overrides (not overwrites) previous definitions
lastSheet.insertRule(newRule, ruleCount);
Making the attributes !important and making this the very last CSS definition should override any previous definition, unless one is more specifically targeted. You may have to insert more rules in that case.
This is similar to aSeptik's answer, but what about this approach? Wrap the CSS code which you want to disable using JavaScript in <noscript> tags. That way if javaScript is off, the CSS :hover will be used, otherwise the JavaScript effect will be used.
Example:
<noscript>
<style type="text/css">
ul#mainFilter a:hover {
/* some CSS attributes here */
}
</style>
</noscript>
<script type="text/javascript">
$("ul#mainFilter a").hover(
function(o){ /* ...do your stuff... */ },
function(o){ /* ...do your stuff... */ });
</script>
I used the not() CSS operator and jQuery's addClass() function. Here is an example, when you click on a list item, it won't hover anymore:
For example:
HTML
<ul class="vegies">
<li>Onion</li>
<li>Potato</li>
<li>Lettuce</li>
<ul>
CSS
.vegies li:not(.no-hover):hover { color: blue; }
jQuery
$('.vegies li').click( function(){
$(this).addClass('no-hover');
});
I'd recommend to replace all :hover properties to :active when you detect that device supports touch. Just call this function when you do so as touch().
function touch() {
if ('ontouchstart' in document.documentElement) {
for (var sheetI = document.styleSheets.length - 1; sheetI >= 0; sheetI--) {
var sheet = document.styleSheets[sheetI];
if (sheet.cssRules) {
for (var ruleI = sheet.cssRules.length - 1; ruleI >= 0; ruleI--) {
var rule = sheet.cssRules[ruleI];
if (rule.selectorText) {
rule.selectorText = rule.selectorText.replace(':hover', ':active');
}
}
}
}
}
}
I would use CSS to prevent the :hover event from changing the appearance of the link.
a{
font:normal 12px/15px arial,verdana,sans-serif;
color:#000;
text-decoration:none;
}
This simple CSS means that the links will always be black and not underlined. I cannot tell from the question whether the change in the appearance is the only thing you want to control.
Try just setting the link color:
$("ul#mainFilter a").css('color','#000');
Edit: or better yet, use the CSS, as Christopher suggested
Actually an other way to solve this could be, overwriting the CSS with insertRule.
It gives the ability to inject CSS rules to an existing/new stylesheet.
In my concrete example it would look like this:
//creates a new `style` element in the document
var sheet = (function(){
var style = document.createElement("style");
// WebKit hack :(
style.appendChild(document.createTextNode(""));
// Add the <style> element to the page
document.head.appendChild(style);
return style.sheet;
})();
//add the actual rules to it
sheet.insertRule(
"ul#mainFilter a:hover { color: #0000EE }" , 0
);
Demo with my 4 years old original example:
http://jsfiddle.net/raPeX/21/
This can be realized by pure javascript easily; Try the code below:
<!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">
<title>Document</title>
</head>
<style>
:root {
--orange-color: #fa8e3f;
--dark-organge-color: #bd5305;
--light-color: #fff;
--dark-color: #000;
--grey-color: #f2f2f2;
--transition: all 300ms ease-in-out;
}
.quiz-options {
list-style-type: none;
margin: 1rem 0;
}
.quiz-options li {
color: var(--light-color);
background-color: var(--orange-color);
font-weight: 600;
border: 3px solid var(--orange-color);
border-radius: .5rem;
margin: .7rem 0;
padding: .4rem 1.2rem;
box-shadow: 0 4px 0 0 var(--dark-organge-color);
transition: var(--transition);
}
.quiz-options li.enable-hover-active {
cursor: pointer;
}
.quiz-options li.enable-hover-active:hover {
background-color: var(--grey-color);
color:var(--dark-color);
border-color: var(--grey-color);
box-shadow: 0 4px 0 0 #bbb;
}
.quiz-options li.enable-hover-active:active {
transform: scale(0.97);
}
button {
border: none;
border-radius: 0.5rem;
outline: 0;
font-family: 'Poppins', sans-serif;
font-size: 1.2rem;
font-weight: 600;
padding: .5rem 1rem;
margin: 0 auto;
text-transform: uppercase;
cursor: pointer;
display: block;
background-color: var(--grey-color);
color: var(--dark-color);
letter-spacing: 2px;
transition: var(--transition);
box-shadow: 0 4px 0 0 #bbb;
}
</style>
<body>
<ul class="quiz-options">
<li>option 1</li>
<li>option 2</li>
<li>option 3</li>
<li>option 4</li>
</ul>
<button type="button" id="check-answer" onclick="enableHoverActive()">Enable hover & active</button>
<script>
function enableHoverActive() {
if (document.getElementById('check-answer').textContent == 'Enable hover & active') {
document.getElementById('check-answer').textContent = 'Disable hover & active';
document.querySelectorAll('li').forEach((option) => {
option.classList.add('enable-hover-active');
});
} else {
document.getElementById('check-answer').textContent = 'Enable hover & active';
document.querySelectorAll('li').forEach((option) => {
option.classList.remove('enable-hover-active');
});
}
}
</script>
</body>
</html>
The result is as below:
when "disabled", hover and click options
when "enabled", hover and click options