My slideshow script uses the onclick event window.location.reload() to advance to the next mini-slideshow, causing the page to flicker when the “NEXT Plant” button is clicked.
Ideally, the onclick event should trigger a function to advance the slideshow, eliminating the need to reload the page.
Creating such a function, unfortunately, is easier said than done.
Intuitively, my first thought was to forego the onclick event window.location.reload() method and instead have the onclick event call the onLoad function runShow(), thinking that re-invoking this script would advance the slideshow. It didn’t.
Re-invoking other functions also failed to advance the slideshow, and now I’m out of ideas what to try next.
Please advise. Thanks.
body {
display: flex;
justify-content: center;
text-align: center;
background-color: black;
}
img {
display: block;
position: relative;
top: 20px;
max-width:100%;
max-height:calc(100vh - 160px - ((.4em + .6vmin) + (.4em + .6vmax)));
object-fit: contain;
}
.caption {
position: absolute;
bottom: 120px;
font-size: calc((.4em + .6vmin) + (.4em + .6vmax));
color: white;
left: 0;
right: 0;
width: 100%;
text-align: center;
}
p {
position: absolute;
bottom: 10px;
left: 0;
right: 0;
width: 100%;
text-align: center;
}
.button {
border-radius: 8px;
background-color: green;
border: none;
color: black;
padding: 10px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
cursor: pointer;
}
<!DOCTYPE html>
<html>
<head>
<title>Plant Slideshow</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
</head>
<body onLoad="runShow()">
<img id="slide" onmouseover="stopShow()" onmouseout="runShow()" src="" alt="">
<script>
var genusSpecies={"Adam's Needle (Yucca filamentosa)":["Adam's Needle (Yucca filamentosa)1.jpg"],"Virginia Wild Rye (Elymus virginicus)":["Virginia Wild Rye (Elymus virginicus)1.jpg","Virginia Wild Rye (Elymus virginicus)2.jpg"]};
if (window.innerHeight > 1000) {
var specificResolution="./plants1220/"; // Higher-resolution photos for desktops
} else {
var specificResolution="./plants500/"; // Lower-resolution photos for smartphones
}
var curimg=0;
var keys=Object.keys(genusSpecies); // Creates array of keys
var plantNumber=Object.keys(genusSpecies).length;
x=Math.floor(Math.random() * (plantNumber)); // Selects random index number for “keys” array, the element’s value providing a named key for “genusSpecies”
var plant=genusSpecies[keys[x]]; // Value of named key (image file names of specific mini-slideshow)
function swapImage()
{
document.getElementById("slide").setAttribute("src",specificResolution+plant[curimg])
curimg=(curimg<plant.length-1)? curimg+1 : 0; timer = setTimeout("swapImage()",4000);
}
function stopShow()
{
clearTimeout(timer);
}
function runShow()
{
swapImage();
}
</script>
<div class="caption">
<script>
document.write(keys[x]); // Displays caption
</script>
</div>
<p><button class="button" onclick="window.location.reload()">NEXT Plant<br>(hover over slideshow to pause)</button></p>
<!-- Reloads page, advancing the slideshow, but is inefficient & causes flickering -->
</body>
</html>
Took a bit of doing to learn how it works.. and because of that I just made a function nextSlide that resets JUST the important stuff(you might wanna do something else other than random though) because your other functions do the rest :D
Pure random next slide makes there be several occurrences of the same slide being loaded.. If you want it not like that(eg: sequentially looping through array) just tell me in the comments, but as for now, your code runs without reloading
EDIT: IT WORKS PERFECTLY, WHAT IS GOING WRONG?
https://repl.it/talk/share/Testing/121825 has code forked from your repl(and I applied my below answer to it) and https://slideshow-code-needs-improving--paultaylor2.repl.co/ would let you see the full tab example(it works, and changes the images).. so I ask, what problems are you experiencing?
I did see one thing, that the value specificResolution are 2 different things from when you gave your snippet in your question and the snippet you have in your repl.. so just ensure that specificResolution checks EXISTING FOLDERS
//place this in a script tag SOMEWHERE AT THE BOTTOM LIKE BELOW BODY
var genusSpecies={"Adam's Needle (Yucca filamentosa)":["Adam's Needle (Yucca filamentosa)1.jpg"],"Virginia Wild Rye (Elymus virginicus)":["Virginia Wild Rye (Elymus virginicus)1.jpg","Virginia Wild Rye (Elymus virginicus)2.jpg"]};
/*HELLO, PLEASE MAKE SURE THIS VARIABLE HAS A VALID BEGINNING, since your example in the repl for this variable is DIFFERENT to the example I'm replicating from your question*/
/////////////////////////////////////////////////
if (window.innerHeight > 1000) {
window.specificResolution="./plants1220/"; // Higher-resolution photos for desktops
} else {
window.specificResolution="./plants500/"; // Lower-resolution photos for smartphones
}
/////////////////////////////////////////////////
var curimg=0;
var keys=Object.keys(genusSpecies); // Creates array of keys
var plantNumber=Object.keys(genusSpecies).length;
var rand=()=>Math.floor(Math.random() * (plantNumber));
var x=rand(); // Selects random index number for “keys” array, the element’s value providing a named key for “genusSpecies”
var plant=genusSpecies[keys[x]]; // Value of named key (image file names of specific mini-slideshow)
function swapImage()
{
document.getElementById("slide").setAttribute("src",specificResolution+plant[curimg])
curimg=(curimg<plant.length-1)? curimg+1 : 0; window.timer = setTimeout(swapImage,4000);
}
function stopShow()
{
clearTimeout(timer);
}
function runShow()
{
swapImage();
}
function nextSlide(){ //your other functions do the rest of work :D
x=rand(); curimg=0;
stopShow(); runShow();
plant=genusSpecies[keys[x]];
document.getElementsByClassName('caption')[0].innerText=(keys[x]);
}
document.getElementsByClassName('caption')[0].innerText=(keys[x]); // Displays caption
body {
display: flex;
justify-content: center;
text-align: center;
background-color: black;
}
img {
display: block;
position: relative;
top: 20px;
max-width:100%;
max-height:calc(100vh - 160px - ((.4em + .6vmin) + (.4em + .6vmax)));
object-fit: contain;
}
.caption {
position: absolute;
bottom: 120px;
font-size: calc((.4em + .6vmin) + (.4em + .6vmax));
color: white;
left: 0;
right: 0;
width: 100%;
text-align: center;
}
p {
position: absolute;
bottom: 10px;
left: 0;
right: 0;
width: 100%;
text-align: center;
}
.button {
border-radius: 8px;
background-color: green;
border: none;
color: black;
padding: 10px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
cursor: pointer;
}
<!DOCTYPE html>
<html>
<head>
<title>Plant Slideshow</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
</head>
<body onLoad="runShow()">
<img id="slide" onmouseover="stopShow()" onmouseout="runShow()" src="" alt="">
<div class="caption"></div>
<p><button class="button" onclick="nextSlide()">NEXT Plant<br>(hover over slideshow to pause)</button></p>
<!-- Reloads page, advancing the slideshow, but is inefficient & causes flickering -->
</body>
</html>
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();
}
});
}
}
I followed a codelab to make a smart webcam for object detection using TensorFlow.js. It was a simple site so later I tried to add some visuals like some colors, headbar, buttons, etc. Now, the webpage is working almost smoothly on my PC screen but I am a lot of problem in running it on a mobile device.
Just to explain what I am trying to do- Firstly, the page with some text loads and downloads the TensorFlow.js model => a button appears => on pressing it the button disappears and a video and two new buttons appear (switch and close camera). Then the model starts working and make bounding boxes.
I am having two problems-
Not able to use rear camera on the mobile.
I am not able to set the position of the video so that it fits both PC and mobile screens.
Link to the webpage- https://lordharsh.github.io/Object-Detection-with-Webcam/
Code-
HTML-
<!DOCTYPE html>
<html lang="en">
<head>
<title>OD using TensorFlow</title>
<meta charset="utf-8">
<!-- Import the webpage's stylesheet -->
<link rel="stylesheet" href="style.css">
<meta name="viewport" content="width=1280, initial-scale=1">
</head>
<body class= "page">
<header>
<a>Multiple Object Detection</a>
</header>
<main>
<p id ='p1' class= 'para'>Multiple object detection using pre trained model in TensorFlow.js. Wait for the model to load before clicking the button to enable the webcam - at which point it will become
visible to use.</p>
<section id="demos" class="invisible">
<p id ='p2'>Hold some objects up close to your webcam to get a real-time classification! When ready click "enable
webcam"
below and accept access to the webcam when the browser asks (check the top left of your window)</p>
<div id="liveView" class="camView">
<button id="webcamButton" class="button b1">ENABLE CAMERA</button>
<video id="webcam" autoplay width="640" height="480"></video>
<button id="webcamFlipButton" class="button b2">SWITCH CAMERA</button>
<button id="webcamCloseButton" class="button b3">CLOSE CAMERA</button>
</div>
</section>
<!-- Import TensorFlow.js library -->
<script src="https://cdn.jsdelivr.net/npm/#tensorflow/tfjs/dist/tf.min.js" type="text/javascript"></script>
<!-- Load the coco-ssd model to use to recognize things in images -->
<script src="https://cdn.jsdelivr.net/npm/#tensorflow-models/coco-ssd"></script>
<!-- Import the page's JavaScript to do some stuff -->
<script src="script.js" defer></script>
</main>
</body>
</html>
JavaScript-
const video = document.getElementById('webcam');
const liveView = document.getElementById('liveView');
const demosSection = document.getElementById('demos');
const enableWebcamButton = document.getElementById('webcamButton');
const flipWebcamButton = document.getElementById('webcamFlipButton');
const closeWebcamButton = document.getElementById('webcamCloseButton');
const para1 = document.getElementById('p1');
para2 = document.getElementById('p2');
let camDirection = 'user';
console.log(window.screen.availHeight+" "+window.screen.availWidth+' '+window.devicePixelRatio);
// Check if webcam access is supported.
function getUserMediaSupported() {
return !!(navigator.mediaDevices &&
navigator.mediaDevices.getUserMedia);
}
// If webcam supported, add event listener to button for when user
// wants to activate it to call enableCam function which we will
// define in the next step.
if (getUserMediaSupported()) {
enableWebcamButton.addEventListener('click', enableCam);
} else {
console.warn('getUserMedia() is not supported by your browser');
}
// Enable the live webcam view and start classification.
function enableCam(event) {
// Only continue if the COCO-SSD has finished loading.
if (!model) {
return;
}
if (event.target === flipWebcamButton) {
if (camDirection === 'user'){
camDirection = 'environment';
console.log('shouls change');
}
else
camDirection = 'user';
}
// Hide the button once clicked.
p1.classList.add('removed');
p2.classList.add('removed');
event.target.classList.add('removed');
video.classList.add('vid_show')
flipWebcamButton.classList.add('show')
closeWebcamButton.classList.add('show')
// getUsermedia parameters to force video but not audio.
const constraints = {
video: {facingMode: { exact: camDirection }}
};
// Activate the webcam stream.
navigator.mediaDevices.getUserMedia(constraints).then(function (stream) {
video.srcObject = stream;
video.addEventListener('loadeddata', predictWebcam);
});
}
flipWebcamButton.addEventListener('click', enableCam);
closeWebcamButton.addEventListener('click', restartPage);
function restartPage(event) {
location.reload()
}
// Store the resulting model in the global scope of our app.
var model = undefined;
// Before we can use COCO-SSD class we must wait for it to finish
// loading. Machine Learning models can be large and take a moment
// to get everything needed to run.
// Note: cocoSsd is an external object loaded from our index.html
// script tag import so ignore any warning in Glitch.
cocoSsd.load().then(function (loadedModel) {
model = loadedModel;
// Show demo section now model is ready to use.
demosSection.classList.remove('invisible');
});
var children = [];
function predictWebcam() {
// Now let's start classifying a frame in the stream.
model.detect(video).then(function (predictions) {
// Remove any highlighting we did previous frame.
for (let i = 0; i < children.length; i++) {
liveView.removeChild(children[i]);
}
children.splice(0);
// Now lets loop through predictions and draw them to the live view if
// they have a high confidence score.
for (let n = 0; n < predictions.length; n++) {
// If we are over 66% sure we are sure we classified it right, draw it!
if (predictions[n].score > 0.66) {
const p = document.createElement('p');
p.style = "font-size=2vh"
p.innerText = predictions[n].class + ' - with '
+ Math.round(parseFloat(predictions[n].score) * 100)
+ '% confidence.';
p.style = 'margin-left: ' + predictions[n].bbox[0] + 'px; margin-top: '
+ (predictions[n].bbox[1] - 10) + 'px; width: '
+ (predictions[n].bbox[2] - 10) + 'px; top: 0; left: 0;';
const highlighter = document.createElement('div');
highlighter.setAttribute('class', 'highlighter');
highlighter.style = 'left: ' + predictions[n].bbox[0] + 'px; top: '
+ predictions[n].bbox[1] + 'px; width: '
+ predictions[n].bbox[2] + 'px; height: '
+ predictions[n].bbox[3] + 'px;';
liveView.appendChild(highlighter);
liveView.appendChild(p);
children.push(highlighter);
children.push(p);
}
}
// Call this function again to keep predicting when the browser is ready.
window.requestAnimationFrame(predictWebcam);
});
}
CSS-
:root {
--primary: #000000;
--secondary: #;
--primaryLight: #2c2c2c;
--primaryDark: #000000;
--secondaryLight: #73ffd8;
--secondaryDark: #00ca77;
}
header {
overflow: hidden;
background-color:black;
position: fixed; /* Set the navbar to fixed position */
top: 0; /* Position the navbar at the top of the page */
width: 1300px; /* Full width */
padding: 5px;
left: 0;
shape-margin: 5px;
text-align: left;
text-shadow: 50px #000000;
}
header a{
padding: 10px;
left: 50px;
font-family:Impact, Haettenschweiler, 'Arial Narrow Bold', sans-serif;
color: whitesmoke;
font-size: 5vh;
font-weight: 400;
letter-spacing: 0.08em;
}
/* Main content */
main {
padding-left: 12px;
margin-top:10vh; /* Add a top margin to avoid content overlay */
text-align: center;
font-size: large;
align-content: center;
text-align: center;
}
.para{
margin-top: 40vh;
}
body {
font-family: "Lucida Console";
color: #ffffff;
background-color: #2c2c2c;
}
video{
display: none;
border-radius: 12px;
align-self: center;
}
.vid_show{
display:block;
align-self: center;
}
section {
opacity: 1;
transition: opacity 500ms ease-in-out;
}
.removed {
display: none;
}
.invisible {
opacity: 0.2;
}
.camView {
vertical-align: middle;
position: relative;
cursor: pointer;
align-content: center;
}
.camView p {
position: absolute;
padding: 5px;
background-color: #1df3c2;
color: #fff;
border: 1px dashed rgba(255, 255, 255, 0.7);
z-index: 2;
font-size: 12px;
align-content: center;
}
.highlighter {
background: rgba(0, 255, 0, 0.25);
border: 1px dashed #fff;
z-index: 1;
position: absolute;
}
.button{
height:max-content;
width: max-content;
color: #000000;
box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2), 0 6px 20px 0 rgba(0,0,0,0.19);
border-radius: 3ch;
left: 50%;
right: 50%;
border-collapse: collapse;
font-size: 1.7vh;
font-weight: bold;
font-family:Verdana, Geneva, Tahoma, sans-serif;
padding: 1vh;
transition-duration: 0.4s;
}
.button:hover {
background-color: #000000;
color: white;
box-shadow: 0 6px 10px 0 rgb(231, 231, 231), 0 6px 10px 0 rgb(231, 231, 231);
}
.b2{
display:none;
}
.b3{
display: none;
}
.show{
display:inline-grid;
}
You can also view this code at-
Link to GitHub Code- https://github.com/LordHarsh/Objecct-Detection-with-Webcam
Sorry for the too long question but I am new to web development.
My original question was marked falsely by another user as a duplicate but the link provided did not answer any parts of the question asked so I will ask another. Making the site builder I ran into an issue where the prompt value when pressing okay is not used as the text in the created h1. Why is this? The class applies and creates all the elements I wanted to but the text is not present on the site at all, and there are no errors in the code because it all works fine.
.new-hd {
position: fixed;
z-index: 5;
bottom: 0;
right: 0;
}
.new-para {
position: fixed;
z-index: 5;
bottom: 0;
left: 0;
}
.classic-hd {
max-width: 100vw;
width: 100vw;
max-height: 15vh;
height: 15vh;
position: absolute;
left: 0;
top: 0;
background-color: black;
display: flex;
align-items: center;
}
#classic-hd-txt {
color: white;
font-family: sans-serif;
text-indent: 3vw;
}
.fa-times {
color: white;
position: absolute;
top: 0.25vh;
right: 1vw;
z-index: 5;
}
<!DOCTYPE html>
<html>
<head>
<title>Make a Site</title>
<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
<link rel="stylesheet" href="path/to/font-awesome/css/font-awesome.min.css">
</head>
<body>
<button type="button" class="new-hd">
Make Header
</button>
<button type="button" class="new-para">
Make Paragraph
</button>
<script>
$(document).ready(function() {
$(".new-hd").click(function() {
var newHdTxt = window.prompt("What would you like your Header Text to be?", "Enter Response Here");
var newHdCont = document.createElement("header");
var newHd = document.createElement("h1");
$(newHdCont).addClass("classic-hd");
$(newHd).addClass("classic-hd-txt");
document.getElementsByClassName("classic-hd-txt").innerHTML = newHdTxt;
document.body.appendChild(newHdCont);
newHdCont.appendChild(newHd);
//alert(newTxt);
});
$(".new-para").click(function() {
document.createElement("p");
});
});
</script>
</body>
</html>
On behalf of Nik who gave the answer, here is the way you resolve this. Instead of using the DOM selector get.ElementsByClassName().innerHTML use the method newHd.innerText = newHdTxt.
use attr function to add id attribute.like this
$jqueryElement.attr('id', 'change_it_to_what_you_want_but_should_be_unique');
I am writing a slider from scratch, no plugins.
I have my slider working, based on adding the slides together and plus or minus the length of the slider window.
It has become complicated when pagination needs to be added. I can't seem to wrap my head around the logic of the function needed to be written that states.
if button 1 is clicked run the function 1 time and go to slide one.
if button 2 is clicked run the function 2 times and go to slide two. .... and so on..
The issue I see coming from this is if on slide 3 and the button 4 is clicked the function only needs to move once not 4 times!! This is where my head breaks and all logic spills out of my ears.
How do I go about writing something like this?
here is the jsfiddle I have so far. http://jsfiddle.net/r5DY8/2/
Any help would be appreciated.
:: all the code on one page if you don't want to use jsfiddle ::
<!DOCTYPE html>
<html>
<head>
<script src='http://code.jquery.com/jquery-1.9.0.min.js'type="text/javascript"></script>
<link href='http://fonts.googleapis.com/css?family=Marmelad' rel='stylesheet' type='text/css'>
<style type="text/css">
body {
font-family: 'Marmelad', sans-serif;
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select:none;
user-select:none;
}
#slideContainer {
position: relative;
width: 990px;
height: 275px;
float: left;
overflow: hidden;
margin-top:5%;
margin-left:15%;
}
#slideWrap {
width: 3960px;
height: 275px;
position: absolute;
top: 0;
left: 0;
}
.slide {
width: 990px;
height: 275px;
float: left;
}
.slide:first-child { background-color: #009999; }
.slide:nth-child(2) { background-color: #CC0033; }
.slide:nth-child(3) { background-color: #FFFF66; }
.slide:nth-child(4) { background-color: #006699; }
#clickLeft{
color: black;
float: left;
margin: 12% 0% 0 15%;
/*background: url("prev.png") no-repeat;*/
width: 60px;
height: 60px;
cursor: pointer;
list-style: none;
position: absolute;
z-index: 9;
border:1px solid black;/**/
}
#clickRight{
color: black;
float: right;
margin: 12% 0 0 79.5%;
/*background: url("next.png") no-repeat;*/
width: 60px;
height: 60px;
cursor: pointer;
list-style: none;
position: absolute;
border:1px solid black;/**/
}
.dots{
width: 9%;
position: absolute;
top: 310px;
text-align: center;
height: 45px;
padding-top: 5px;
background: white;
left: 43.5%;
border-radius: 8px;
list-style:none;
}
.dots li {
display: inline-block;
list-style:none;
}
.dots li:first-child {
margin-left:-40px;
}
.dots li a{
width: 16px;
height: 16px;
display: block;
background: #ededed;
cursor: pointer;
-webkit-border-radius: 20px;
-moz-border-radius: 20px;
-o-border-radius: 20px;
border-radius: 20px;
margin: 5px;
}
.dots li a:hover { background: rgba(0, 0, 0, 0.7); }
.styleDots { background: #a4acb2; }
.active { background: #a4acb2;
-webkit-border-radius: 20px;
-moz-border-radius: 20px;
-o-border-radius: 20px;
border-radius: 20px;}
li.pagerItem{
}
</style>
<script type="text/javascript">
$(function(){
var currentSlidePosition = 0;
var slideW = 990;
var allSlides = $('.slide');
var numberOfSlides = allSlides.length;
var marker;
$('.slide').each(function(i) {
listNumber=i+1;
marker = $("<li>");
marker.addClass('pagerItem '+listNumber);
$("<a href='#' ></a>").appendTo(marker);
if (i===0){
marker.addClass('active');
}
marker.appendTo($(".dots"));
});
allSlides.wrapAll('<div id="moveSlide"></div>').css({'float' : 'left','width' : slideW});
$('#moveSlide').css('width', slideW * numberOfSlides);
$('body').prepend('<li class="controls" id="clickLeft"></li>')
.append('<li class="controls" id="clickRight"></li>');
$('.controls').click(function(){
moveSlide(this);
moveSlide(this); // running twice because the function is being called twice
//create a function that says if button 1 is clicked run the function 1 time if button 3 is clicked run the function 3 times..
});
var moveSlide = function(thisobject){
console.log('function run');
if(($(thisobject).attr('id')=='clickRight')) {
if(currentSlidePosition == numberOfSlides-1)currentSlidePosition=0;
else currentSlidePosition++;
var active = $(".active").removeClass('active');
if(active.next() && active.next().length){
active.next().addClass('active');
} else {
active.siblings(":first").addClass('active');
}
} else if($(thisobject).attr('id')=='clickLeft'){
if(currentSlidePosition == 0)currentSlidePosition=numberOfSlides-1;
else currentSlidePosition--;
var active = $(".active").removeClass('active');
if(active.prev() && active.prev().length){
active.prev().addClass('active');
} else {
active.siblings(":last").addClass('active');
}
}
$('#moveSlide').animate({'margin-left' : slideW*(-currentSlidePosition)});
}
});
</script>
</head>
<body>
<div id="slideContainer">
<div id="slideWrap">
<div class="slide">1</div>
<div class="slide">2</div>
<div class="slide">3</div>
<div class="slide">4</div>
</div>
</div>
<ul class="dots"></ul>
</body>
</html>
It's more complicated than just calling the function a number of times. As the animation is asynchronous, you need to call the function again when the animation has finished, not right away.
Add a callback parameter to the function so that it can use that do do something when the animation finishes:
var moveSlide = function (thisobject, callback) {
Add the callback to the animation:
$('#moveSlide').animate({
'margin-left': slideW * (-currentSlidePosition)
}, callback);
Make a function moveTo that will call moveSlide in the right direction, and use itself as callback:
function moveTo(target){
if (target < currentSlidePosition) {
moveSlide($('#clickLeft'), function(){ moveTo(target); });
} else if (target > currentSlidePosition) {
moveSlide($('#clickRight'), function(){ moveTo(target); });
}
}
Bind the click event to the links in the dots. Use the index method to find out which slide you want to go to, and call moveTo to do it:
$('.dots a').click(function(e){
e.preventDefault();
var target = $(this).parent().index();
moveTo(target);
});
Fiddle: http://jsfiddle.net/Guffa/r5DY8/3/
From a purely logical point of view (assumes the existence of two variables - curr_slide_num and butt_num):
for (var i=0; i < Math.abs(curr_slide_num - butt_num); i++) my_func();
Be careful of zero indexing; either treat the first button and first slide as number 0, or neither, else the maths will break down.
This takes no account of the direction the slider should move. I haven't looked at your Fiddle but I guess you would pass direction as an argument to the function. Let's say the function expects direction as its first argument - the string 'left' or 'right'
for (var i=0; i < Math.abs(curr_slide_num - butt_num); i++)
my_func(curr_slide_num < butt_num ? 'left' : 'right');
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.