Okay, I change the appearance of links using JavaScript. When I change the content of a hard-coded link, it sticks in that the changed color and underlining remains when the cursor is not hovering above it. However, when the content of a DIV has been changed using JavaScript, the style changes do not stick.
Here is the HTML code:
<!doctype html>
<html>
<head>
<title>Bla bla</title>
<meta charset="UTF-8">
<link href="style/kim.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="scripts/Kim.js"></script>
</head>
<body>
<div class="wrapper">
<div class="main">
<div class="nav">
<div class="topNav">
<ul>
<li onClick="changeNav('design')">Design</li>
<li onClick="changeNav('code')">Programming</li>
<li onClick="changeNav('science')">Science</li>
<li onClick="changeNav('Kim')">Kim</li>
</ul>
</div>
<div id="subNav">
<script>changeNav("design");</script>
</div>
</div>
<div class="content">
<p id="mainText">Test</p>
</div>
</div>
</div>
</body>
</html>
Here is the JS code:
var topNavNames = ["design", "code", "science", "Kim"];
var subNavCode = ["<ul><li onClick=\"loadPHP('design/websites.php', 'sub0')\">Websites</li><li onClick=\"loadPHP('design/graphics.php', 'sub1')\">Graphics</li><li onClick=\"loadPHP('design/flash.php', 'sub2')\">Flash</li></ul>",
"<ul><li onClick=\"loadPHP('code/interactive.php', 'sub0')\">Interactive applets</li><li onClick=\"loadPHP('code/statistics.php', 'sub1')\">Statistics</li><li onClick=\"loadPHP('code/wings.php', 'sub2')\">Wings</li><li onClick=\"loadPHP('code/3D.php', 'sub3')\">3D</li></ul>",
"<ul><li onClick=\"loadPHP('science/3D.php', 'sub0')\">3D</li><li onClick=\"loadPHP('science/ssd.php', 'sub1')\">Sexual Size Dimorphism</li><li onClick=\"loadPHP('science/shape.php', 'sub2')\">Wing shape</li><li onClick=\"loadPHP('science/phylogenetics.php', 'sub3')\"><i>Drosophila</i> phylogenetics</li><li onClick=\"loadPHP('science/communitygenetics.php', 'sub4')\">Community Genetics</li><li onClick=\"loadPHP('science/biodiversity.php', 'sub5')\">Biodiversity</li></ul>",
"<ul><li onClick=\"loadPHP('Kim.php', 'sub0')\">Who is Kim?</li><li onClick=\"loadPHP('animals/horses.php', 'sub1')\">Horses</li><li onClick=\"loadPHP('animals/birds.php', 'sub2')\">Birds</li><li onClick=\"loadPHP('private/outdoors.php', 'sub3')\">Outdoors</li><li onClick=\"loadPHP('contact.php', 'sub4')\">Contact</li></ul>"];
function changeNav(target) {
for (var i = 0; i<topNavNames.length; i++) {
if (target == topNavNames[i]) {
document.getElementById("subNav").innerHTML=subNavCode[i];
document.getElementById(topNavNames[i]).style.color="#F7EDAA";
document.getElementById(topNavNames[i]).style.borderBottom="thin solid #F7EDAA";
}
else {
document.getElementById(topNavNames[i]).style.color="#EEE";
document.getElementById(topNavNames[i]).style.borderBottom="thin solid #111";
}
}
}
function loadPHP(url, target) {
for (var i = 0; i<10; i++) {
if(document.getElementById(target)!=null) {
if (("sub"+i) == target) {
document.getElementById(target).style.color="#F7EDAA";
document.getElementById(target).style.borderBottom="thin solid #F7EDAA";
}
else {
document.getElementById(target).style.color="#EEE";
document.getElementById(target).style.borderBottom="thin solid #111";
}
}
}
}
if I subsequently remove the:
else {
document.getElementById(target).style.color="#EEE";
document.getElementById(target).style.borderBottom="thin solid #111";
}
from the loadPHP function, it changes the style, but does not reset it when the next link is clicked.
I observed this behavior in FireFox, Internet Exploder and Chrome.
Added: CSS code:
body {
background-color: #111111;
color: #DDD;
font-family: "Gill Sans", "Gill Sans MT", "Myriad Pro", "DejaVu Sans Condensed", Helvetica, Arial, sans-serif;
}
.wrapper {
overflow: auto;
}
.banner {
float: left;
position: relative;
width: 100px;
}
.main {
position: relative;
width: 80%;
left: 25px;
font-size: 14px;
font-weight: normal;
}
a {
text-decoration: none;
color: #EEE;
}
a:hover {
border-bottom: thin solid #F7EDAA !important;
color: #F7EDAA !important;
}
.topNav {
height: 45px;
position: relative;
left: 100px;
font-size: large;
border: thin solid #111;
}
#subNav {
height: 45px;
position: relative;
left: 100px;
top: 2px;
border: thin solid #111;
}
.topNav li, #subNav li {
float: left;
margin: 10px 15px;
}
.topNav ul, #subNav ul {
list-style: none;
padding: 0px 0px;
margin: 0px 0px;
position: relative;
left: -100px;
}
.content {
position: relative;
left: 15px;
padding: 0px 0px;
margin: 0px 0px;
}
.content p {
padding: 5px 5px;
margin: 10px 15px;
left: -100px;
}
In my opinion you´re using the wrong technology to achieve your goal. What you need to do is to write your styles in a css stylesheet, and then add or remove classes to your elements using js if you want. (You can also do this through something called specificity, a little far ahead from the scope of your question)
Also think that if there is some bug in your script, or a third party script called in your page, JS may break and it won´t process your styling changes.
So, add the basic styling to your elements through css in the initial markup, so you will be sure that your elements will have always a basic styling, and then if you want use the equivalent to .addClass or removeClass jQuery methods.
In that way you will be always sure that your frontend will have always a safe styling, won´t break if js is not loaded, and separation of concerns will be properly implemented.
Regards.
I figured it out. The following code does not do the right thing:
function loadPHP(url, target) {
for (var i = 0; i<subNavNames.length; i++) {
if (target == subNavNames[i]){
document.getElementById(target).className="selected";
} else {
document.getElementById(target).className="notSelected";
}
}
While this code does produce the right result:
function loadPHP(url, target) {
for (var i = 0; i<subNavNames.length; i++) {
if (target == subNavNames[i]) {
document.getElementById(subNavNames[i]).className="selected";
} else {
document.getElementById(subNavNames[i]).className="notSelected";
}
}
The difference is that in the first example, and in the example of the original question, I use the variable passed on in the method (target), to find the element. In the second, I use the appropriate element from a array that I have added to the list. I am not sure WHY this behaves differently, but it does.
Related
By the way, this is coming from a beginner coder, so don't expect any great amount of organization. I may have missed something obvious.
I couldn't get it to work here as a snippet (for security reasons, it won't allow images to be loaded, not even showing the failing to load icon), so I made a copy of it here.
The issue is that, while hovering over a folder, it works fine, but when I begin hovering over the menu that pops up while hovering over the folder, it starts flashing rapidly. Yes, the menu is supposed to delete itself when the user stops hovering over the folder and show when the user hovers over the folder.
HTML code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Something</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<link href='https://fonts.googleapis.com/css?family=Poppins' rel='stylesheet'>
</head>
<body>
<!-- See CSS code for more explanation -->
<div class="sidebar">
<h1 style="padding: 1vw;">Todo</h1>
<div class="folder">
Folder 1
</div>
<div class="folder">
Folder 2
</div>
<div class="folder">
Folder 3
</div>
<div class="addBtn">+ Folder</div>
</div>
<script src="script.js"></script>
</body>
</html>
CSS code:
/* might have something to do with css; please read my hastily made comments */
/* self explanatory */
html,body {
height: 100%;
margin: 0px;
padding: 0px;
background-color: black;
}
/* sets some defaults */
* {
padding: 0px;
margin: 0px;
border: 0px;
overflow: hidden;
font-family: Poppins;
background-color: inherit;
}
/* sets text selection color to nothing */
*::selection {
background: inherit;
}
/* styling for the sidebar (the part that says "todo", shows folders, etc.) */
.sidebar {
background: #9caeb0;
display: inline-block;
width: calc(20% - 2vw);
height: 100vh;
padding: 1vw;
}
/* the text that says todo */
h1 {
font-size: 30px;
font-weight: 700;
}
/* a folder. */
.folder {
width: calc(15.4vw);
background-color: #8c9ca3;
padding: .6vw;
padding-left: 1.25vw;
padding-right: 1.25vw;
border-radius: 0px 5px 5px 0px;
font-weight: 200;
cursor: pointer;
transition: .45s;
margin: .6vw;
margin-left: -1vw;
margin-right: calc(0vw);
font-size: 15px;
position: relative;
}
/* uses css animations to change the folder upon hovering */
.folder:hover {
background-color: #75828a;
cursor: pointer;
margin-top: .8vw;
margin-bottom: .8vw;
margin-left: -2vw;
padding-left: 2.25vw;
width: 15.8vw;
font-size: 17px;
}
/* the add folder button */
.addBtn {
width: 15.4vw;
background-color: rgba(0,0,0,0);
padding: .6vw;
padding-left: 1.25vw;
padding-right: 1.25vw;
border-radius: 0px 5px 5px 0px;
font-weight: 200;
cursor: pointer;
transition: .45s;
margin-left: -1vw;
font-size: 15px;
border: 3px solid #8c9ca3;
border-left: 0;
/*position: absolute;
bottom: 4vh;*/
}
/* changes bg color upon hovering over add folder button */
.addBtn:hover {
background-color: #8c9ca3;
}
.smallMenu {
position: absolute;
height: 17px;
top: 50%;
width: 17px;
-ms-transform: translateY(-50%);
transform: translateY(-50%);
right: 0.5vw;
border-radius: 99px;
}
.menuBtn {
position: absolute;
height: 14px;
top: 1.5px;
left: 7px;
padding: 0px;
margin: 0px;
}
JS Code:
// probably can ignore these functions; scroll down to line 45; there's a lot of code here for purposes that I haven't quite finished yet
function inLocalStorage(item) {
if(!localStorage.getItem(item)) {
return false;
} else {
return true;
}
}
function lsAdd(label,value) {
localStorage.setItem(label, value);
}
function lsGet(item) {
return localStorage.getItem(item);
}
function lsClear() {
localStorage.clear();
}
function lsRemove(item) {
localStorage.removeItem(item);
}
var el;
var mouseOver = false;
// checks if the user has visited
if (!inLocalStorage('visited')) {
alert("Don't mind this alert");
lsAdd('visited','yes');
lsAdd('folders','1');
lsAdd('js','');
} else {
// load from local storage; execute stored JS
new Function(lsGet('js'))();
// upon mouseover of folder, show mini menu icon
for (let i = 0; i < document.getElementsByClassName("folder").length; i++) {
document.getElementsByClassName("folder")[i].addEventListener("click", function() {
console.log("You have clicked.");
});
// add menu upon mouseover
document.getElementsByClassName("folder")[i].addEventListener("mouseover", function() {
mouseOver = false;
el = document.createElement("div");
// this image obviously doesn't load but that's not important; the image is an svg with three vertical dots, and the image is transparent
el.innerHTML = '<div class="smallMenu"><img src="abc.svg" class="menuBtn" style="height:14px;"></div>';
el.setAttribute("id","menu");
document.getElementsByClassName('folder')[i].appendChild(el);
el = document.getElementsByClassName('smallMenu')[0];
el.addEventListener('mouseover', function() {
mouseOver = true;
console.log(mouseOver);
});
el.addEventListener('mouseout', function() {
mouseOver = false;
console.log(mouseOver);
});
});
// remove menu upon mouse out
document.getElementsByClassName("folder")[i].addEventListener("mouseout", function() {
if (mouseOver === false) {
el = document.getElementById("menu");
el.remove();
}
});
}
}
So, i am having an issue with a div, when another div is generated (via javascript) below it, it is changing the size of the div.
// for the side nav message list
const chatList = function(list) {
let br = document.createElement("br")
for (let index in list) {
try {
let chat = list[index]
let chatBodyParent = document.createElement("div")
chatBodyParent.onclick = function() {
$("#message-list").empty()
api.listMessages(chat.chat.id)
document.getElementById("message-list").channelId = chat.chat.id
}
chatBodyParent.id = `chat-body-${chat.chat.id}`
let chatBody = document.createElement("div")
chatBody.className = "chat-body"
let chatImg = document.createElement("img")
chatImg.src = chat.chat.cover
if (!chat.chat.cover && chat.chat.type == 1) {
chatImg.src = "/dump/pfp.svg"
}
if (!chat.chat.cover && chat.chat.type == 3) {
chatImg.src = "/dump/public.png"
}
chatImg.className = "chat-img"
chatImg.setAttribute("align", "left")
chatBody.appendChild(chatImg)
let chatInfoContainer = document.createElement("div")
chatInfoContainer.className = "chat-info-container"
let chatName = document.createElement("span")
chatName.className = "chat-name"
chatName.innerText = chat.chat.title
chatInfoContainer.appendChild(chatName)
chatInfoContainer.appendChild(br.cloneNode(true))
let chatMessageContent = document.createElement("span")
chatMessageContent.className = "chat-message-content"
chatMessageContent.id = `chat-message-content-${chat.chat.id}`
let messageContent
if (chat.message) {
let long = false;
if (chat.message.text.length >= 30) {
long = true
}
messageContent = chat.message.text.substring(0, 30)
if (long) {
messageContent += "..."
}
} else if (chat.type == "file") {
messageContent = chat.user.nick + " sent a file"
}
chatMessageContent.innerText = messageContent
chatInfoContainer.appendChild(chatMessageContent)
chatBody.appendChild(chatInfoContainer)
chatBodyParent.appendChild(chatBody)
document.getElementById("chat-list").appendChild(chatBodyParent)
} catch {
console.log(list[index])
}
}
}
.sidenav {
height: 100%;
width: 15%;
position: fixed;
z-index: 1;
top: 0;
left: 0;
background-color: var(--lightish-grey);
overflow-x: hidden;
padding-top: 20px;
}
.sidenav a {
padding: 6px 8px 6px 16px;
text-decoration: none;
font-size: 25px;
color: #818181;
display: block;
}
.sidenav a:hover {
color: #f1f1f1;
}
.main {
margin-left: 15%;
padding: 0px 10px;
overflow-x: hidden;
}
#media screen and (max-height: 450px) {
.sidenav {padding-top: 15px;}
.sidenav a {font-size: 18px;}
}
::-webkit-scrollbar {
color: var(--grey);
}
::-webkit-scrollbar-corner {
color: var(--grey);
}
::-webkit-scrollbar-track {
color: var(--grey);
}
.menu {
width: 90%;
min-width: 90%;
height: 200px;
margin-left: 5%;
margin-right: 5%;
background-color: var(--menu-grey);
padding-top: 10px;
padding-bottom: 5px;
font-family: "FontRegular";
}
.chat-bar {
position: fixed;
bottom: 1%;
width: 50%;
height: 3.5%;
padding: 0px 5px;
margin: 8px 0;
display: inline-block;
border-top: hidden;
border-left: hidden;
border-right: hidden;
border-bottom: solid var(--light-grey);
box-sizing: border-box;
background-color: var(--grey);
color: var(--light-grey);
font-family: "FontRegular";
}
.chat-bar:focus {
outline-width: 0;
}
.chat-body {
width: 90%;
height: 50px;
margin-left: 5%;
border: 3px;
border-top: hidden;
border-left: hidden;
border-right: hidden;
/*border-bottom: solid var(--light-grey);*/
padding-top: 10px;
padding-bottom: 5px;
font-family: "FontRegular";
}
.chat-body:hover {
opacity: 0.8;
cursor:pointer;
}
.chat-body:focus {
opacity: 0.8;
}
.chat-img {
height: 50px;
width: auto;
border-radius: 50%;
}
.chat-info-container {
position:relative;
top: 10%;
}
<!DOCTYPE html>
<html>
<head>
<title>iFChat - Dashboard</title>
<link rel="stylesheet" href="/css/index.css">
<link rel="stylesheet" href="/css/dashboard.css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="/js/utils.js"></script>
<script type="text/javascript" src="/js/api.js"></script>
<script type="text/javascript" src="/js/dashboard.js"></script>
</head>
<div class="sidenav">
<div id="menu" class="menu">
</div>
<div>
</div> <br><br>
<div id="chat-list">
</div>
</div>
<div class="main" id="main">
<div id="message-list" class="message-list">
</div>
<input type="text" name="chat..." id="chat-bar" class="chat-bar" placeholder="chat..." maxlength="500">
</div>
</html>
Here is an image before the chat list is loaded
Then menu is loaded with the correct size and margin
pre-load
after the chat list loads, it changes the width or margin of the div above some how, and im not sure how or why its doing that, but i cant figure it out, heres an image of after the chat list is loaded post-load
i have tried different margins and positioning settings but cant seem to get it to work, any help is greatly appreciated :)
edit: One possible solution may be to change the css with javascript every time the chat list is loaded, but i would like to avoid that if at all possible.
OK, so i figured out the issue, the issue occurs when enough elements pop up to trigger the scrollbar, so the fix for me was this
::-webkit-scrollbar {
display: none;
}
Because i want a user to beable to scroll, but i dont want there to be a scrollbar, My next plan is to make this static, so that it doesnt move on scroll at all. Still the issue was arising when my (invisible scroll bar, that still had a width) was appearing. Gotta watch out for hidden elements.
This code is the untouched version of a FAQ consisting of three answers that can be shown or hidden when click on it. My task is to modify to show only one answer at a time (the other two must close).
I got a hint to use a for loop to go through the h2 elements in the array and remove the class attribute for all h2 elements that aren’t the one that has been clicked.
Thank you,
"use strict";
var $ = function(id) { return document.getElementById(id); };
// the event handler for the click event of each h2 element
var toggle = function() {
var h2 = this; // clicked h2 tag
var div = h2.nextElementSibling; // h2 tag's sibling div tag
// toggle plus and minus image in h2 elements by adding or removing a class
if (h2.hasAttribute("class")) {
h2.removeAttribute("class");
} else {
h2.setAttribute("class", "minus");
}
// toggle div visibility by adding or removing a class
if (div.hasAttribute("class")) {
div.removeAttribute("class");
} else {
div.setAttribute("class", "open");
}
};
window.onload = function() {
// get the h2 tags
var faqs = $("faqs");
var h2Elements = faqs.getElementsByTagName("h2");
// attach event handler for each h2 tag
for (var i = 0; i < h2Elements.length; i++ ) {
h2Elements[i].onclick = toggle;
}
// set focus on first h2 tag's <a> tag
h2Elements[0].firstChild.focus();
};
HTML for the script:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>FAQs</title>
<link rel="stylesheet" href="main.css">
<script src="faqs.js"></script>
</head>
<body>
<main id="faqs">
<h1>JavaScript FAQs</h1>
<h2><a href="#" >What is JavaScript?</a></h2>
<div>
<p>JavaScript is a programming language that's built into the major web browsers.
It makes web pages more responsive and saves round trips to the server.
</p>
</div>
<h2>What is jQuery?</h2>
<div>
<p>jQuery is a library of the JavaScript functions that you're most likely
to need as you develop web sites.
</p>
</div>
<h2>Why is jQuery becoming so popular?</h2>
<div>
<p>Three reasons:</p>
<ul>
<li>It's free.</li>
<li>It lets you get more done in less time.</li>
<li>All of its functions are cross-browser compatible.</li>
</ul>
</div>
</main>
</body>
</html>
And CSS for the script:
* {
margin: 0;
padding: 0;
}
body {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 87.5%;
width: 650px;
margin: 0 auto;
border: 3px solid blue;
padding: 15px 25px;
}
h1 {
font-size: 150%;
}
h2 {
font-size: 120%;
padding: .25em 0 .25em 25px;
cursor: pointer;
background: url(images/plus.png) no-repeat left center;
}
h2.minus {
background: url(images/minus.png) no-repeat left center;
}
a {
color: black;
text-decoration: none;
}
a:focus, a:hover {
color: blue;
}
div {
display: none;
}
div.open {
display: block;
}
ul {
padding-left: 45px;
}
li {
padding-bottom: .25em;
}
p {
padding-bottom: .25em;
padding-left: 25px;
}
Something like the following might do the trick assuming your existing script/markup is currently working. I can't test my answer without the HTML/CSS.
Essentially it just iterates over the faq items when ones clicked and hides them if they aren't the element that was clicked or shows if it is the element clicked - it won't toggle if the same element is clicked twice - one will always remain open.
"use strict";
var $ = function(id) { return document.getElementById(id); };
// the event handler for the click event of each h2 element
window.onload = function() {
// get the h2 tags
var faqs = $("faqs");
var h2Elements = faqs.getElementsByTagName("h2");
function accordionClick(){
var h2;
for(var i=0; i < h2Elements.length; i++){
h2 = h2Elements[i];
if(h2 == this){ // The item we clicked
if(!h2.hasAttribute("class")){ // If it's open
closeItem(h2);
} else{ // If not
openItem(h2);
}
} else{ // Not the item we clicked so it should be closed
closeItem(h2);
}
}
}
function openItem(h2){
var div = h2.nextElementSibling;
h2.removeAttribute("class")
div.setAttribute("class", "open");
}
function closeItem(h2){
var div = h2.nextElementSibling;
h2.setAttribute("class", "minus")
div.removeAttribute("class");
}
// attach event handler for each h2 tag and init classes
for (var i = 0; i < h2Elements.length; i++ ) {
h2Elements[i].onclick = accordionClick;
closeItem(h2Elements[i]);
}
// set focus on first h2 tag's <a> tag
h2Elements[0].firstChild.focus();
};
* {
margin: 0;
padding: 0;
}
body {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 87.5%;
width: 650px;
margin: 0 auto;
border: 3px solid blue;
padding: 15px 25px;
}
h1 {
font-size: 150%;
}
h2 {
font-size: 120%;
padding: .25em 0 .25em 25px;
cursor: pointer;
background: url(images/plus.png) no-repeat left center;
}
h2.minus {
background: url(images/minus.png) no-repeat left center;
}
a {
color: black;
text-decoration: none;
}
a:focus, a:hover {
color: blue;
}
div {
display: none;
}
div.open {
display: block;
}
ul {
padding-left: 45px;
}
li {
padding-bottom: .25em;
}
p {
padding-bottom: .25em;
padding-left: 25px;
}
<main id="faqs">
<h1>JavaScript FAQs</h1>
<h2><a href="#" >What is JavaScript?</a></h2>
<div>
<p>JavaScript is a programming language that's built into the major web browsers.
It makes web pages more responsive and saves round trips to the server.
</p>
</div>
<h2>What is jQuery?</h2>
<div>
<p>jQuery is a library of the JavaScript functions that you're most likely
to need as you develop web sites.
</p>
</div>
<h2>Why is jQuery becoming so popular?</h2>
<div>
<p>Three reasons:</p>
<ul>
<li>It's free.</li>
<li>It lets you get more done in less time.</li>
<li>All of its functions are cross-browser compatible.</li>
</ul>
</div>
</main>
I have thoroughly searched MapBox support and Stack Overflow for an answer on how to create an exclusive layer switcher using the latest MapBox API (1.6.1 as of now). Exclusive in this case means that only 1 layer can be visible/active at a time. I do not want to use the Leaflet Layers Control for design reasons.
With a little help, I have come up with this example, which almost works:
http://bl.ocks.org/sarahkhank/0e5d81998d2d0876856c
For some reason, adding and removing the gridControl breaks the loop. If you use this structure to just add/remove the tileLayer with no gridLayer or gridControl, it works fine. But when you add the grid elements, the last element in the array doesn't show up and messes up the rest of the loop. (In this case 'far'.)
Does anyone have any idea why this is happening? This type of layer switcher is often asked about on MapBox support, so I'm sure many people would be happy to see this come to life. Thanks for your help!!
Posting full code here at the bottom in case my bl.ocks link ever breaks.
<html>
<head>
<title>DC Zoning Map</title>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src='http://api.tiles.mapbox.com/mapbox.js/v1.6.1/mapbox.js'></script>
<link href='http://api.tiles.mapbox.com/mapbox.js/v1.6.1/mapbox.css' rel='stylesheet' />
</head>
<body>
<style>
#zoning-map-container {
position:relative;
float: right;
display: inline;
}
#map_zoning {
position: relative;
float: left;
clear: both;
width:45%;
min-width: 500px;
height: 500px;
right:20px;
margin-top: 10px;
margin-right: 10px;
border: 1px solid #bbb;
}
#map-ui-zoning {
position:relative;
float: left;
list-style:none;
margin:0;padding:0;
left: -20px;
}
#map-ui-zoning a {
font-family: 'Carrois Gothic', sans-serif;
font-size: 12px;
font-weight: 400;
background:#FFF;
color:#5698D0;
float: left;
margin:0;
border:1px solid #BBB;
border-width: 1px 1px 1px 0;
max-width:100px;
padding:8px;
text-decoration:none;
}
#map-ui-zoning li {
display: inline;
}
#map-ui-zoning a:hover { background:#ECF5FA; }
#map-ui-zoning li:last-child a {
border-bottom-width:1px;
-webkit-border-radius:0 3px 3px 0;
border-radius:0 3px 3px 0;
}
#map-ui-zoning li:first-child a {
border-left-width: 1px;
-webkit-border-radius:3px 0 0 3px;
border-radius:3px 0 0 3px;
}
#map-ui-zoning a.active {
background:#5698D0;
border-color:#5698D0;
border-top-color:#BBB;
color:#FFF;
}
.map-tooltip .zone {
font-size: 10px;
line-height: 13px;
font-weight: bold;
}
.map-tooltip .desc {
font-size: 10px;
line-height: 13px;
padding-bottom: 3px;
}
.map-tooltip .focus {
font-size: 13px;
line-height: 16px;
font-weight: bold;
}
.map-tooltip .info {
font-size: 11px;
line-height: 16px;
}
</style>
<div id='zoning-map-container'>
<ul id='map-ui-zoning'>
<li>Maximum Stories</li>
<li>Maximum Height</li>
<li>Maximum FAR</li>
</ul>
<div id='map_zoning'></div>
</div>
<script type='text/javascript'>
var map = L.mapbox.map('map_zoning');
var stamenLayer = L.tileLayer('https://stamen-tiles-{s}.a.ssl.fastly.net/toner-lite/{z}/{x}/{y}.png', {
attribution: 'Map tiles by Stamen Design, under CC BY 3.0. Data by OpenStreetMap, under CC BY SA.'
}).addTo(map);
map.setView([38.908, -77.029], 11);
var ui = document.getElementById('map-ui-zoning');
var stories = L.mapbox.tileLayer('sarah.28n6ogvi');
var storiesGrid = L.mapbox.gridLayer('sarah.28n6ogvi');
var storiesGridControl = L.mapbox.gridControl(storiesGrid, {follow: false});
var height = L.mapbox.tileLayer('sarah.ofjsv2t9');
var heightGrid = L.mapbox.gridLayer('sarah.ofjsv2t9');
var heightGridControl = L.mapbox.gridControl(heightGrid, {follow: false});
var far = L.mapbox.tileLayer('sarah.2w9x80k9');
var farGrid = L.mapbox.gridLayer('sarah.2w9x80k9');
var farGridControl = L.mapbox.gridControl(farGrid, {follow: false});
var layers = [{
'name': 'stories',
'layer': stories,
'gridLayer': storiesGrid,
'gridControl': storiesGridControl
},
{
'name': 'height',
'layer': height,
'gridLayer': heightGrid,
'gridControl': heightGridControl
},
{
'name': 'far',
'layer': far,
'gridLayer': farGrid,
'gridControl': farGridControl
}
];
$(document).ready(function(layer){
map.addLayer(stories);
map.addLayer(storiesGrid);
map.addControl(storiesGridControl);
});
$('#map-ui-zoning li a').on('click', function() {
$('#map-ui-zoning li a').removeClass('active');
var $el = $(this);
layers.forEach(function(layer) {
if ($el.data('name') !== layer['name']){
map.removeLayer(layer['layer']);
map.removeLayer(layer['gridLayer']);
map.removeControl(layer['gridControl']);
}
else {
map.addLayer(layer['layer']);
map.addLayer(layer['gridLayer']);
map.addControl(layer['gridControl']);
$el.addClass('active');
}
});
});
</script>
I think that when you call map.removeControl(layer['gridControl']) or more generally map.removeLayer you dont test if the layer is already added to the map because otherwise it mapboxjs will try to delete an element that does not exist and this is where your code gets broken .
if ($el.data('name') !== layer['name'])
needs to become
if ($el.data('name') !== layer['name'] && map.hasLayer(layer))
of course you need to change your else statement accordingly .
here is your example running
http://bl.ocks.org/radproject/31c48b1a7610e353d495
I've written this jQuery code that fades in a overlay with some links over an image. What i found out is that it is painfully slow when I add like 10 of these images. I would really appreciate some tips and tricks on how to make this code faster.
If you have some tips for my HTML and CSS that would be great too ;)
jQuery code
$(document).ready(function() {
var div = $(".thumb").find("div");
div.fadeTo(0, 0);
div.css("display","block");
$(".thumb").hover(
function () {
$(this).children(".download").fadeTo("fast", 1);
$(this).children(".hud").fadeTo("fast", 0.7);
},
function () {
div.fadeTo("fast", 0);
}
);
});
All the code
<style type="text/css">
a:active {
outline:none;
}
:focus {
-moz-outline-style:none;
}
img {
border: none;
}
#backgrounds {
font: 82.5% "Lucida Grande", Lucida, Verdana, sans-serif;
margin: 50px 0 0 0;
padding: 0;
width: 585px;
}
.thumb {
margin: 5px;
position: relative;
float: left;
}
.thumb img {
background: #fff;
border: solid 1px #ccc;
padding: 4px;
}
.thumb div {
display: none;
}
.thumb .download {
color: #fff;
position: absolute;
top: 0;
left: 0;
z-index: 999;
padding: 0 10px;
}
.thumb .download h3 {
font-size: 14px;
margin-bottom: 10px;
margin-top: 13px;
text-align: center;
}
.thumb .download a {
font-size: 11px;
color: #fff;
text-decoration: none;
font-weight: bold;
line-height: 16px;
}
.thumb .download a:hover {
text-decoration: underline;
}
.thumb .download .left, .thumb .download .right {
width: 44%;
margin: 0;
padding: 4px;
}
.thumb .download .left {
float: left;
text-align: right;
}
.thumb .download .right {
float: right;
text-align: left;
}
.thumb img, .thumb .hud {
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
}
.thumb .hud {
width: 100%;
height: 110px;
position: absolute;
top: 0;
left: 0;
background: #000;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var div = $(".thumb").find("div");
div.fadeTo(0, 0);
div.css("display","block");
$(".thumb").hover(
function () {
$(this).children(".download").fadeTo("fast", 1);
$(this).children(".hud").fadeTo("fast", 0.7);
},
function () {
div.fadeTo("fast", 0);
}
);
});
</script>
<div id="backgrounds">
<div class="thumb">
<div class="download">
<h3>Download wallpaper</h3>
<p class="left">
1024x768
1280x800
1280x1024
</p>
<p class="right">
1440x900
1680x1050
1920x1200
</p>
</div>
<div class="hud"></div>
<img alt="image" src="thumb.jpg"/>
</div>
</div>
I got it to respond a little better by simply changing the following within the hover(..):
function () {
$(".download", this).fadeTo("fast", 1);
$(".hud", this).fadeTo("fast", 0.7);
},
function () {
$(".download, .hud", this).fadeTo("fast", 0);
}
The biggest difference comes from only applying the hoverout effect to the event target, no need to reapply to all your divs on the page.
I've put your code into a test page and to be perfectly honest, even with thirty or so .thumb divs it seemed ok - certainly responsive enough to use from my end. Sliding the mouse over a bunch of them means I have to wait for the rollover effect to go through them all which takes a while until it gets to the one I've actually stopped on, but surely that was what you wanted given that you're using 'hover' rather than 'click' (which would certainly remove any speed issues).
I'm not using actual images in my test page, just getting the alt text, so my best current guess would be to make sure all images you're loading are as small filesize as you can possibly make them.
Pre-Select MORE
Good job preselecting the div. Try this way so that it pre-selects the fade in elements as well instead of doing it on hover:
$().ready(function() {
var div = $(".thumb").find("div");
div.fadeTo(0, 0);
div.css("display","block");
$(".thumb").each(function() {
var download = $(this).children(".download");
var hud = $(this).children(".hud");
$(this).hover(
function () {
download.fadeTo("fast", 1);
hud.fadeTo("fast", 0.7);
},
function () {
div.fadeTo("fast", 0);
}
);
});
});
try removing the
:focus {
-moz-outline-style:none;
}
and see what happens