jQuery mouseenter and mouseleave handler not working properly - javascript

I have been trying desperately to solve my problem and I just don't find the mistake in my code. So what I am programming is a slider which works with jQuery and I had everything precisely as I wanted it but then I made some completely irrelevant changes and it didn't work any more. My issue is that (as you can see in the jsfiddle) the arrows to navigate the slider don't (always) show up. They only show up at the very end of the Interval (see jsfiddle). Am I doing something wrong with the .mouseenter and .mouseleave-handlers?
Would you recommend using the `.hover-handler?
Thanks in advance
JSFiddle: http://jsfiddle.net/VincentBS/ogm967bz
And if that helps: Here is the website the slider is programmed for
$(document).ready(function(){
hideArrows();
hideImages();
$(".back").click(function(){prevImage()});
$(".pre").click(function(){nextImage()});
$("#slider").mouseenter(function(){
//showArrows();
$(".back").show();
$(".pre").show();
})
$("#slider").mouseleave(function(){
//hideArrows();
$(".back").hide();
$(".pre") .hide();
})
start();
});
function hideArrows(){
$(".back").hide();
$(".pre") .hide();
}
function showArrows(){
$(".back").show();
$(".pre") .show();
}
function hideImages(){
$("#2").hide();
$("#3").hide();
$("#4").hide();
$("#5").hide();
}
function start(){
// save when we started for calculating progress
var startedAt = Date.now();
// set animation bounds
var startValue = 1;
var endValue = 100;
// figure out how much change we have over the whole animation
var delta = endValue - startValue;
// Animation function, to run at 60 fps.
t = setInterval(function(){
// How far are we into the animation, on a scale of 0 to 1.
var progress = (Date.now() - startedAt) / 5000;
// If we passed 1, the animation is over so clean up.
if (progress > 1) {
nextImage();
}
}, 1000 / 60);
}
function prevImage(){
var id = document.getElementsByClassName("activeslider")[0].id;
var next = parseInt(id) - 1;
if(next < 1){next = 5}
next = "#" + next.toString();
id = "#" + id.toString();
$(id).removeClass("activeslider").fadeOut();
$(next).addClass("activeslider").fadeIn();
clearInterval(t);
start();
}
function nextImage(){
var id = document.getElementsByClassName("activeslider")[0].id;
var next = parseInt(id) + 1;
if(next > 5){next = 1}
next = "#" + next.toString();
id = "#" + id.toString();
$(id).removeClass("activeslider").fadeOut();
$(next).addClass("activeslider").fadeIn();
clearInterval(t);
start();
}
#slider {
float: left;
width: 700px;
height: 233px;
}
.back, .pre {
background-color: #EB5A00;
opacity: 1;
margin-top: 92px;
color: #FFF;
font-size: 25px;
text-align: center;
padding: 12.5px 7.5px;
cursor: pointer;
z-index: 1001;
}
.back {
float: left;
margin-left: 10px;
}
.pre {
float: right;
margin-right: 10px;
}
#slider, .back, .pre {
-webkit-user-drag: none;
-moz-user-select: none;
user-drag: none;
}
.sliderimage {
width: 100%;
}
#slider img {
position: absolute;
width: 700px;
-webkit-user-drag: none;
-moz-user-select: none;
user-drag: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="slider">
<img class="sliderimage activeslider" src="http://dev.hvgg.de/file_upload/data15749.jpg" id="1" />
<img class="sliderimage" src="http://dev.hvgg.de/file_upload/data15750.jpg" id="2" />
<img class="sliderimage" src="http://dev.hvgg.de/file_upload/data15751.jpg" id="3" />
<img class="sliderimage" src="http://dev.hvgg.de/file_upload/data15752.jpg" id="4" />
<img class="sliderimage" src="http://dev.hvgg.de/file_upload/data15753.jpg" id="5" />
<span class="back">◀</span>
<span class="pre">▶</span>
</div>

Position problem I have change some css property
#slider {
float: left;
width: 700px;
height: 233px;
position: relative;
}
.back, .pre {
background-color: #EB5A00;
opacity: 1;
color: #FFF;
font-size: 25px;
position: absolute;
text-align: center;
padding: 12.5px 7.5px;
cursor: pointer;
z-index: 1001;
}
.back {
left: 0;
margin-left: 10px;
top: 50%;
}
.pre {
margin-right: 10px;
right: 0;
top: 50%;
}
#slider, .back, .pre {
-webkit-user-drag: none;
-moz-user-select: none;
user-drag: none;
}
.sliderimage {
width: 100%;
}
#slider img {
position: absolute;
width: 700px;
-webkit-user-drag: none;
-moz-user-select: none;
user-drag: none;
}
http://jsfiddle.net/ogm967bz/1/

I have tweaked your CSS a bit of .back, .pre
$(document).ready(function(){
hideArrows();
hideImages();
$(".back").click(function(){prevImage()});
$(".pre").click(function(){nextImage()});
$("#slider").mouseenter(function(){
//showArrows();
$(".back").show();
$(".pre").show();
})
$("#slider").mouseleave(function(){
//hideArrows();
$(".back").hide();
$(".pre") .hide();
})
start();
});
function hideArrows(){
$(".back").hide();
$(".pre") .hide();
}
function showArrows(){
$(".back").show();
$(".pre") .show();
}
function hideImages(){
$("#2").hide();
$("#3").hide();
$("#4").hide();
$("#5").hide();
}
function start(){
// save when we started for calculating progress
var startedAt = Date.now();
// set animation bounds
var startValue = 1;
var endValue = 100;
// figure out how much change we have over the whole animation
var delta = endValue - startValue;
// Animation function, to run at 60 fps.
t = setInterval(function(){
// How far are we into the animation, on a scale of 0 to 1.
var progress = (Date.now() - startedAt) / 5000;
// If we passed 1, the animation is over so clean up.
if (progress > 1) {
nextImage();
}
}, 1000 / 60);
}
function prevImage(){
var id = document.getElementsByClassName("activeslider")[0].id;
var next = parseInt(id) - 1;
if(next < 1){next = 5}
next = "#" + next.toString();
id = "#" + id.toString();
$(id).removeClass("activeslider").fadeOut();
$(next).addClass("activeslider").fadeIn();
clearInterval(t);
start();
}
function nextImage(){
var id = document.getElementsByClassName("activeslider")[0].id;
var next = parseInt(id) + 1;
if(next > 5){next = 1}
next = "#" + next.toString();
id = "#" + id.toString();
$(id).removeClass("activeslider").fadeOut();
$(next).addClass("activeslider").fadeIn();
clearInterval(t);
start();
}
#slider {
float: left;
width: 700px;
height: 233px;
}
.back, .pre {
background-color: #EB5A00;
opacity: 1;
top: 92px; /* Chnages here */
color: #FFF;
font-size: 25px;
text-align: center;
padding: 12.5px 7.5px;
cursor: pointer;
z-index: 1001;
position:absolute; /* Chnages here */
}
.back {
float: left;
left: 10px; /* Chnages here */
}
.pre {
float: right;
right: 10px; /* Chnages here */
}
#slider, .back, .pre {
-webkit-user-drag: none;
-moz-user-select: none;
user-drag: none;
}
.sliderimage {
width: 100%;
}
#slider img {
position: absolute;
width: 700px;
-webkit-user-drag: none;
-moz-user-select: none;
user-drag: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="slider">
<img class="sliderimage activeslider" src="http://dev.hvgg.de/file_upload/data15749.jpg" id="1" />
<img class="sliderimage" src="http://dev.hvgg.de/file_upload/data15750.jpg" id="2" />
<img class="sliderimage" src="http://dev.hvgg.de/file_upload/data15751.jpg" id="3" />
<img class="sliderimage" src="http://dev.hvgg.de/file_upload/data15752.jpg" id="4" />
<img class="sliderimage" src="http://dev.hvgg.de/file_upload/data15753.jpg" id="5" />
<span class="back">◀</span>
<span class="pre">▶</span>
</div>

Refer : http://jsfiddle.net/ogm967bz/8/
add the following css in the file
position:relative;
under the
.back, .pre {
background-color: #EB5A00;
opacity: 1;
margin-top: 92px;
color: #FFF;
font-size: 25px;
text-align: center;
padding: 12.5px 7.5px;
cursor: pointer;
z-index: 1001;
cursor: pointer;
position:relative;
}

Related

How do I make an extension's html background invisible?

I´m trying to do a test extension for chrome for a university project but I can´t find a way to make the background or body of the extension´s html completely invisible, just for a clean interface. The problems I´m having are those white corners on the background.
This is the code of the extension:
// Define variables
let audio, playbtn, title, poster, artists, mutebtn, seekslider, volumeslider,
seeking = false, seekto, curtimetext, durtimetext, playlist_status, dir, playlist,
ext, agent, playlist_artist, repeat, randomSong;
// Initialization of YouTube Api
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
var id = '5_385OOZlIg';
var url = 'https://www.youtube.com/watch?v=' + id;
// Initialization of Array of Music, Tittle, Poster Image, Artists
dir = "music/";
playlist = ["Cartoon-On-_-On","Elektronomia","Johnning","Popsicle","Fearless"];
title = ["Cartoon - On & On","Elektronomia","Janji-Heroes Tonight","Popsicle","Lost Sky - Fearless"];
artists = ["(feat. Daniel Levi) [NSC Release]","Elektronomia - Sky High [NCS Release]","(feat. Johnning) [NCS Release]",
"LFZ - [NCS Release]","(feat. Chris Linton)[NCS Release]"];
poster = ["images/ncs1.jpeg","images/ncs2.jpg","images/ncs3.jpg","images/ncs4.jpg","images/ncs5.jpg"];
// Used to run on every browser
ext = ".mp3";
agent = navigator.userAgent.toLowerCase();
if(agent.indexOf('firefox') != -1 || agent.indexOf('opera') != -1){
ext = ".ogg";
}
// Set object references
playbtn = document.getElementById("playpausebtn");
nextbtn = document.getElementById("nextbtn");
prevbtn = document.getElementById("prevbtn");
mutebtn = document.getElementById("mutebtn");
visibilitybtn = document.getElementById("visibility");
seekslider = document.getElementById("seekslider");
volumeslider = document.getElementById("volumeslider");
curtimetext = document.getElementById("curtimetext");
durtimetext = document.getElementById("durtimetext");
playlist_status = document.getElementById("playlist_status");
playlist_artist = document.getElementById("playlist_artist");
repeat = document.getElementById("repeat");
randomSong = document.getElementById("random");
playlist_index = 0;
// Audio Object
audio = new Audio();
audio.src = dir + playlist[0] + ext; // music/musicname.mp3
audio.loop = false;
// First song title and artist
playlist_status.innerHTML = title[playlist_index];
playlist_artist.innerHTML = artists[playlist_index];
// Add event handling
playbtn.addEventListener("click", playPause);
nextbtn.addEventListener("click", nextSong);
prevbtn.addEventListener("click", prevSong);
mutebtn.addEventListener("click", mute);
visibilitybtn.addEventListener("click", toggle);
seekslider.addEventListener("mousedown", function(event){seeking = true; seek(event);});
seekslider.addEventListener("mousemove", function(event){seek(event);});
seekslider.addEventListener("mouseup", function(){seeking = false;});
volumeslider.addEventListener("mousemove", setvolume);
audio.addEventListener("timeupdate", function(){seektimeupdate();});
audio.addEventListener("ended",function(){switchTrack();});
repeat.addEventListener("click", loop);
randomSong.addEventListener("click", random);
// Functions
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '315',
width: '560',
videoId: id,
playerVars: {'autoplay': 0, 'controls': 0, 'loop': 1},
events: {
'onStateChange': onPlayerStateChange
}
});
}
/*
function onPlayerReady(event) {
let pgd = player.getDuration();
let vpb = document.getElementById("video_progress_bar");
vpb.setAttribute("max",pgd);
}*/
//Intento de que la barra de progreso avance con forme al video onPlayerStateChange(event) y onPlay()
var testThread;
function onPlayerStateChange(event) {
if(event.data == 1)
{
testThread = setInterval(seektimeupdate,500);
}else{
clearInterval(testThread);
}
}
// Oculta o hace visible el video de YouTube en la interfaz
function toggle(element){
let ventana = document.getElementById("player");
if(ventana.style.display != 'none'){
ventana.style.display = 'none';
}else{
ventana.style.display = '';
}
}
function fetchMusicDetails(){
// Poster Image, Pause/Play Image
$("#playpausebtn img").attr("src", "images/pause-red.png");
$("#bgImage").attr("src", poster[playlist_index]);
$("#image").attr("src",poster[playlist_index]);
// Title and Artist
playlist_status.innerHTML = title[playlist_index];
playlist_artist.innerHTML = artists[playlist_index];
// Audio
audio.src = dir + playlist[playlist_index] + ext;
audio.play();
}
function playPause(element){
let playButton = document.getElementById("playpausebtn");
if(playButton.value == "play"){
playButton.setAttribute("value","pause");
player.playVideo()
$("#playpausebtn img").attr("src","images/pause-red.png");
}else{
playButton.setAttribute("value","play");
player.pauseVideo();
$("#playpausebtn img").attr("src","images/play-red.png");
}
}
function nextSong(){
playlist_index++;
if(playlist_index > playlist.length - 1){
playlist_index = 0;
}
fetchMusicDetails();
}
function prevSong(){
playlist_index--;
if(playlist_index < 0){
playlist_index = playlist.length - 1;
}
fetchMusicDetails();
}
function mute(){
if(player.isMuted()){
player.unMute();
$("#mutebtn img").attr("src","images/speaker.png");
}else{
player.mute();
$("#mutebtn img").attr("src","images/mute.png");
}
}
function seek(event){
if(player.getDuration() == 0){
null;
}else{
if(seeking){
seekslider.value = event.clientX - seekslider.offsetLeft;
seekto = player.getDuration() * (seekslider.value / 100);
player.seekTo(seekto);
}
}
}
function setvolume(){
player.setVolume(volumeslider.value);
}
function seektimeupdate(){
if(player.getDuration()){
let nt = player.getCurrentTime() * (100 / player.getDuration());
seekslider.value = nt;
var curmins = Math.floor(player.getCurrentTime() / 60);
var cursecs = Math.floor(player.getCurrentTime() - curmins * 60);
var durmins = Math.floor(player.getDuration() / 60);
var dursecs = Math.floor(player.getDuration() - durmins * 60);
if(cursecs < 10){cursecs = "0" + cursecs}
if(dursecs < 10){dursecs = "0" + dursecs}
if(curmins < 10){curmins = "0" + curmins}
if(durmins < 10){durmins = "0" + durmins}
curtimetext.innerHTML = curmins + ":" + cursecs;
durtimetext.innerHTML = durmins + ":" + dursecs;
}else{
curtimetext.innerHTML = "00" + ":" + "00";
durtimetext.innerHTML = "00" + ":" + "00";
}
}
function switchTrack(){
if(playlist_index == (playlist.length -1)){
playlist_index = 0;
}else{
playlist_index++;
}
fetchMusicDetails();
}
function loop(){
if(audio.loop){
audio.loop = false;
$("#repeat img").attr("src", "images/rep.png");
}else{
audio.loop = true;
$("#repeat img").attr("src", "images/rep1.png");
}
}
function getRandomNumber(min, max){
let step1 = max - min + 1;
let step2 = Math.random() * step1;
let result = Math.floor(step2) + min;
return result;
}
function random(){
let randomIndex = getRandomNumber(0 , playlist.length - 1);
playlist_index = randomIndex;
fetchMusicDetails();
}
body{
margin: 0;
padding: 0;
height: 100vh;
width: 100%;
background-color: rgba(0,0,0,0);
font-family: 'Poppins', sans-serif;
}
button{
border: none;
outline: none;
background: none;
cursor: pointer;
}
.music-container{
height: 100vh;
width: 100%;
display: flex;
justify-content: center;
align-items: center;
}
.music-content{
position: relative;
width: 245px;
height: 450px;
background-color: #000;
border-width: 8px 4px !important;
border: solid;
border-radius: 20px;
overflow: hidden;
box-shadow: 5px 5px 10px rgba(0, 0, 0, .52);
}
#bg-image img{
width: 110%;
height: 110%;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
z-index: 1;
filter: blur(6px);
-webkit-filter: blur(5px);
}
#blacklayer{
height: 450px;
width: 100%;
background-color: rgba(0,0,0,.404);
position: absolute;
z-index: 2;
}
#menu{
position: relative;
z-index: 3;
padding: 15px;
display: flex;
justify-content: space-between;
align-items: center;
}
#menu img{
width: 15px;
height: 15px;
cursor: pointer;
}
#volume-container{
position: relative;
width: 100%;
height: 15px;
z-index: 3;
display: flex;
justify-content: center;
align-items: center;
}
#volume-container img{
width: 16px;
height: 16px;
margin: 0 5px;
}
.slider{
width: 110px;
height: 1px !important;
-webkit-appearance: none;
border-radius: 10px;
background-color: #fff;
z-index: 100;
outline: none;
position: relative;
}
.slider::-webkit-slider-thumb{
-webkit-appearance: none;
width: 10px;
height: 10px;
background-color: #e62c2f;
border-radius: 50%;
cursor: pointer;
outline: none;
transform: scale(1);
}
.slider:active::-webkit-slider-thumb{
transform: scale(1.2);
}
#music-image{
position: relative;
width: 100%;
height: 215px;
z-index: 3;
}
#circle-image{
position: absolute;
top: -33%;
left: 50%;
transform: translate(-50%,50%);
width: 120px;
height: 120px;
background-color: #000;
border-radius: 50%;
border: 5px solid rgba(221,221,221,0.897);
overflow: hidden;
}
#music-image img{
width: 100%;
height: 100%;
}
#player{
position: absolute;
top: -33%;
left: 50%;
transform: translate(-50%,27%);
width: 120px;
height: 120px;
background-color: #000;
border-radius: 50%;
border: 5px solid rgba(221,221,221,0.897);
overflow: hidden;
}
#music-title{
position: relative;
padding: 0 25px;
top: 65%;
color: #fff;
}
#music-title h5{
color: #fff;
font-size: 20px;
margin: 20px 0 5px;
font-weight: 300;
text-align: center;
line-height: 1.2;
}
#music-title h6{
margin: 0;
font-size: 12.5px;
text-align: center;
font-weight: 400;
}
#music-menu{
width: 90%;
height: 40px;
position: relative;
z-index: 3;
display: flex;
justify-content: space-around;
align-items: center;
margin: 0 auto;
}
#music-menu img{
width: 15px;
height: 15px;
cursor: pointer;
}
#visibility{
width: 20px;
height: 20px;
cursor: pointer;
}
#currentTime{
position: relative;
z-index: 3;
padding: 0 12px 5px;
color: #fff;
display: flex;
justify-content: space-between;
margin-top: 8px;
}
#currentTime span{
font-size: 12px;
}
.seekslider{
width: 100px;
height: 2px !important;
-webkit-appearance: none;
border-radius: 10px;
background-color: #fff;
z-index: 3;
outline: none;
position: fixed;
margin-left: 70px;
}
.seekslider::-webkit-slider-thumb{
-webkit-appearance: none;
width: 10px;
height: 10px;
background-color: #e62c2f;
border-radius: 50%;
cursor: pointer;
outline: none;
transform: scale(1);
}
.seekslider:active::-webkit-slider-thumb{
transform: scale(1.2);
}
#buttons{
position: relative;
width: 100%;
height: 50px;
z-index: 3;
margin-top: 20px;
}
#buttons div{
display: flex;
justify-content: center;
align-items: center;
}
.play{
width: 60px;
height: 50px;
margin: 0 5px;
}
.play img{
width: 100%;
height: 100%;
}
.prev img,
.next img{
width: 20px;
height: 20px;
}
#buttons .like{
position: absolute;
top: 25%;
right: 8%;
cursor: pointer;
}
#buttons .like i{
color: rgba(255,255,255,0.883);
}
#buttons .repeat{
position: absolute;
top: 30%;
left: 6%;
font-size: 15px;
cursor: pointer;
}
#repeat img{
width: 16px;
height: 16px;
}
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset="UTF-8">
<title>Music Player</title>
<link rel="stylesheet" href="css/style.css" type="text/css">
</head>
<body>
<div class="music-container">
<div class="music-content">
<div id="bg-image">
<div id="blackLayer"></div>
<img src="images/ncs1.jpeg" alt="" id="bgImage">
</div>
<div id="menu">
<img src="images/menu.png" alt="">
<img src="images/search.png" alt="">
</div>
<div id="volume-container">
<img src="images/volume-low.png" alt="" id="volumn-down">
<input type="range" class="slider" id="volumeslider" min="0" max="100" value="100" step="1">
<img src="images/volumn-high.png" alt="" id="volumn-up">
</div>
<div id="music-image">
<div id="circle-image">
<div id="player"></div>
<img src="images/ncs1.jpeg" alt="" id="image">
</div>
<div id="music-title">
<h5 id="playlist_status"></h5>
<h6 id="playlist_artist"></h6>
</div>
</div>
<div id="music-menu">
<button id="random"><img src="images/random.png" alt=""></button>
<button id="visibility"><img src="images/video-on.png" alt=""></button>
<button id="mutebtn"><img src="images/speaker.png" alt=""></button>
</div>
<div id="currentTime">
<span id="curtimetext">00:00</span>
<span id="durtimetext">00:00</span>
</div>
<input type="range" class="seekslider" id="seekslider" min="0" max="100" value="0" step="1">
<div id="buttons">
<button class="repeat" id="repeat"><img src="images/rep.png" alt=""></button>
<div>
<button class="prev" id="prevbtn"><img src="images/backward.png" alt=""></button>
<button class="play" id="playpausebtn" value="play"><img src="images/play-red.png" alt=""></button>
<button class="next" id="nextbtn"><img src="images/forward.png" alt=""></button>
</div>
<span class="like">
<i class="far fa-heart" aria-hidden="true"></i>
</span>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="js/main.js"></script>
</body>
</html>
<!-- begin snippet: js hide: false console: true babel: false -->
// Manifest.json
{
"manifest_version" : 2,
"name" : "OdisseyChromeExtension",
"description" : "Reproductor de musica youtube",
"version" : "0.3",
"browser_action" : {
"default_popup" : "index.html",
"default_title" : "odissey"
},
"content_security_policy": "script-src 'self' https://www.youtube.com/iframe_api https://www.youtube.com/s/player/9f996d3e/www-widgetapi.vflset/www-widgetapi.js https://code.jquery.com/jquery-3.5.1.min.js; object-src 'self'",
"permissions": [
"activeTab",
"storage",
"tabs",
"http://*/*" , "https://*/*",
"cookies",
"identity",
"identity.email"
]
}
This is the extension appearance
Okey this might actually solve your problem.
As the background is there because of the iframe, embed a player into an <object> or <video> tag..
<object width={ width } height={ height }>
<video src={ playlists['mylist'].JSON[index].source } type="video/webp" width="100%" height="333" objectFit="cover" />
</object>
Then just get a JSON of the playlist. If you want higher functionality like search or managment of user created playlists you need to go through Googles Data API. It can be finicky in the beggining but well worth the time.
here are some code examples:
https://developers.google.com/youtube/v3/docs/playlists/list?apix=true
Otherwise if you have set playlists in the player, you can just datamine separately and create your own JSON arrays, even manually its really simple and won't even take a minute per list when you have your mining snippet. A small upside here is you can dynamically create custom playlists outside of youtube.
then you can have three players and have them preload the previous and next video for a smoother switching experience ( an option for a fade inbetween can also be nice )
I have snippets of code somewhere for this kind of setup, if this sounds like something you care to do I can try to dig them up for you.
happy coding! :)

Why I have to click 2 times to run this function?

This is the code i'm working on, and i don't know why everytime that i refresh the page i need to click 2 times to open the menu. Once i click the second time all works correctly.
This is the html of the button:
var x = document.getElementById("overlay-menu");
x.style.height = "0%";
function showMenu() {
var x = document.getElementById("overlay-menu");
if (x.style.height === "0%") {
x.style.height = "100%";
} else {
x.style.height = "0%";
}
}
.overlay-menu {
width: 100%;
height: 0%;
padding: 0;
margin: 0;
background-color: #ffffff;
z-index: 10000;
position: fixed;
color: #0A0A0A;
overflow: hidden;
display: block;
transition: .5s cubic-bezier(.55, .03, .26, 1.01);
}
.nav-menu-text {
width: fit-content;
height: fit-content;
margin: 0;
padding: 0;
color: #EB761D;
font-size: 15px;
position: relative;
top: 2.8em;
cursor: pointer;
}
<p class="nav-menu-text" onclick="showMenu()">MENU</p>
<div class="overlay-menu" id="overlay-menu">
<!-- code of the menu -->
</div>
x.style.height is probably not "0%" when your code runs, try changing the condition from:
if (x.style.height === "0%") {
to
if (x.style.height !== "100%") {

CSS - Absolute and Relative Position with image fader

I'm working with an image fader program, but I'm not understanding absolute positioning. I have the images fading nicely and resizing the way I want if the screen resizes. but I have 2 problems. Div#2 gets covered up by the images. I want div2 to always appear below the image div. Also, I have control buttons on the images. I want them in the middle. I thought using top:50% would do that, but it's not. Here's an example...
var slides = document.querySelectorAll('#slides .slide');
var currentSlide = 0;
var slideInterval = setInterval(nextSlide,5000);
function nextSlide(){goToSlide(currentSlide+1);}
function previousSlide(){goToSlide(currentSlide-1);}
function goToSlide(n){
slides[currentSlide].className = 'slide';
currentSlide = (n+slides.length)%slides.length;
slides[currentSlide].className = 'slide showing';}
var next = document.getElementById('next');
var previous = document.getElementById('previous');
next.onclick = function(){nextSlide();};
previous.onclick = function(){previousSlide();};
#slides {position: relative}
.slide{
position: absolute;
left: 0px;
top: 0px;
width:100%;
height:auto;
min-height:300px;
object-fit:cover;
opacity: 0;
box-sizing:border-box;
transition: opacity 2s;}
.showing{opacity: 1;}
.controls{
background: transparent;
color: #fff;
font-size: 30px;
cursor: pointer;
border: 1px solid #555;
width: 30px;
position: absolute;
}
.controls:hover{ opacity:.5}
.fadenext{right: 10px; top: 50%;}
.fadeprev{left: 10px; top: 50%;}
<br><br>
<div id="slides">
<img src='https://www.panotools.org/dersch/Monp.JPG' class="slide showing">
<img src='https://www.panotools.org/dersch/StBp.JPG' class="slide">
<button class="controls fadeprev" id="previous"><</button>
<button class="controls fadenext" id="next">></button>
</div>
<div style='margin-top:40px;border:1px solid red;width:200px;height:100px'>
This is Div # 2</div>
I've amended your snippet to fix your issues.
Adding margin-top instead of top will fix your issue with the
controls.
Div 2 will now always remain below your slider.
P.S. I moved your div2 inline styles to keep it neat.
var slides = document.querySelectorAll('#slides .slide');
var currentSlide = 0;
var slideInterval = setInterval(nextSlide, 5000);
function nextSlide() {
goToSlide(currentSlide + 1);
}
function previousSlide() {
goToSlide(currentSlide - 1);
}
function goToSlide(n) {
slides[currentSlide].className = 'slide';
currentSlide = (n + slides.length) % slides.length;
slides[currentSlide].className = 'slide showing';
}
var next = document.getElementById('next');
var previous = document.getElementById('previous');
next.onclick = function() {
nextSlide();
};
previous.onclick = function() {
previousSlide();
};
* {
margin: 0;
padding: 0;
}
#slides {
position: relative
}
.slide {
position: absolute;
left: 0px;
top: 0px;
width: 100%;
height: auto;
min-height: 300px;
object-fit: cover;
opacity: 0;
box-sizing: border-box;
transition: opacity 2s;
}
.showing {
opacity: 1;
}
.controls {
background: transparent;
color: #fff;
font-size: 30px;
cursor: pointer;
border: 1px solid #555;
width: 30px;
position: absolute;
}
.controls:hover {
opacity: .5
}
.fadenext {
right: 10px;
margin-top: 25%;
}
.fadeprev {
left: 10px;
margin-top: 25%;
}
.div2 {
margin-top: 50%;
border: 1px solid red;
width: 200px;
height: 100px;
}
<br><br>
<div id="slides">
<img src='https://www.panotools.org/dersch/Monp.JPG' class="slide showing">
<img src='https://www.panotools.org/dersch/StBp.JPG' class="slide">
<button class="controls fadeprev" id="previous"><</button>
<button class="controls fadenext" id="next">></button>
</div>
<div class="div2">This is Div # 2</div>
It's not feasible to use % based positions when you use "top" style. So to achieve what you want to do, use margin-top instead. As shown below:
.fadenext{right: 10px; margin-top: 25%;}
.fadeprev{left: 10px; margin-top: 25%;}
And for your div2, just change it's style to:
margin-top: 50%

Converting to the ajax async false alternative because of depreciation

I've done a research on this question and found some solutions. However, not every one of them worked. As I understand, async false makes a UI block, which shouldn't be. I could use an overlay until ajax request is completed and on the request success, hide the overlay.
That was my try using a callback argument in the getNewQuote() function (only a small snippet of it):
var getNewQuote = function(callback) {
var quote = {};
setTimeout(function() {
quote.text = 'Example';
quote.author = 'Example';
callback();
return quote;
}, 4000);
};
getNewQuote(function() {
console.log("DONE");
var getRandomColor = function() {
var colors = [
"#ff9966",
"#7f00ff",
"#396afc",
"#0cebeb",
"#06beb6",
"#642b73",
"#36d1dc",
"#cb356b",
"#3a1c71",
"#ef3b36",
"#159957",
"#000046",
"#007991",
"#56ccf2",
"#f2994a",
"#e44d26",
"#4ac29a",
"#f7971e",
"#34e89e",
"#6190e8",
"#3494e6",
"#ee0979"
],
randomNumber = Math.floor(Math.random() * colors.length);
return colors[randomNumber];
};
var updateText = function($t, qt) {
var twitter = "https://twitter.com/intent/tweet?hashtags=quotes&related=freecodecamp&text=";
twitter += '"' + qt.text + '" ';
twitter += qt.author;
var tumblr = "https://www.tumblr.com/widgets/share/tool?posttype=quote&tags=quotes,freecodecamp&caption=";
tumblr += qt.author;
tumblr += "&content=";
tumblr += qt.text;
tumblr += "&canonicalUrl=https%3A%2F%2Fwww.tumblr.com%2Fbuttons&shareSource=tumblr_share_button";
var $icon = $("<i class='fa fa-quote-left'>")
.prop("aria-hidden", true);
$t.find(".quote-text").html("").append($icon, qt.text);
$t.find(".quote-author").html("- " + qt.author);
$("#tweet-quote").attr("href", twitter);
$("#tumblr-quote").attr("href", tumblr);
};
var calcNewHeight = function(q) {
var $temp = $("<div>", {
class: "quote-container temp",
}).appendTo($("body"));
$temp.append($("<div>", {
class: "quote-text"
}), $("<div>", {
class: "quote-author"
}));
updateText($temp, q);
var h = $temp.height() + 40;
$temp.remove();
return h;
};
var changeColor = function(newColor) {
$("body, .button:not(#new-quote)").animate({
backgroundColor: newColor
});
$("#new-quote").animate({
color: newColor
});
$(".quote-text, .quote-author").css("color", newColor);
if ($("#modStyle").length === 0) {
$("head").append(
"<style id='modStyle'>#new-quote:before {background:" + newColor + ";}</style>"
);
} else {
$("head style#modStyle").html("#new-quote:before {background:" + newColor + ";}");
}
};
var getQuote = function() {
var nq, nc, nh = 0;
nq = getNewQuote();
nc = getRandomColor();
nh = calcNewHeight(nq);
$(".quote-container").children().css("opacity", 0);
changeColor(nc);
$(".quote-container, #new-quote").animate({
height: nh,
}, {
duration: 1000,
queue: false
});
$(".quote-container").animate({
padding: "2.5em"
}, {
duration: 1000,
queue: false
});
$("#new-quote").animate({
padding: "2.5em .75em"
}, {
duration: 1000,
queue: false
});
updateText($(".quote-container"), nq);
$(".quote-container").children().fadeTo(750, 1);
};
$("#new-quote").on("click", getQuote);
$(".quote-container, #new-quote").css({
visibility: "visible",
height: 0
});
$("#new-quote").css("padding", "0 .75em");
getQuote();
});
html,
body {
height: 100%;
width: 100%;
}
body {
margin: 0;
padding: 0;
background: #333;
color: #333;
font-family: sans-serif;
}
.v-wrap {
height: 100%;
text-align: center;
}
.v-wrap:before {
content: "";
display: inline-block;
vertical-align: middle;
width: 0;
height: 100%;
}
.quote-container {
width: 31.25rem;
background: #fff;
margin: 0;
display: inline-block;
vertical-align: middle;
border-radius: 0.1875rem;
border-top-right-radius: 0;
border-bottom-right-radius: 0;
visibility: hidden;
padding: 0 2.5rem;
}
.quote-text {
font-size: 1.625rem;
}
.quote-text i {
margin-right: 0.6rem;
}
.quote-text p {
display: inline;
}
.quote-author {
font-size: 1rem;
margin: 0 0.4rem 2rem 0;
text-align: right;
}
.button {
padding: 0.75rem;
text-align: center;
font-size: 1rem;
color: #fff;
border-radius: .1875rem;
display: inline-block;
cursor: pointer;
-webkit-user-select: none;
user-select: none;
}
.button:not(#new-quote):hover {
opacity: .8 !important;
}
.button:not(#new-quote) {
min-width: 1rem;
min-height: 1rem;
}
.button i {
vertical-align: middle;
}
#new-quote {
white-space: nowrap;
writing-mode: vertical-lr;
height: 50%;
border-top-left-radius: 0;
border-bottom-left-radius: 0;
vertical-align: middle;
background: #fff !important;
margin: 0;
position: relative;
right: 0.25625rem;
color: #333;
visibility: hidden;
}
#new-quote:before {
content: "";
position: absolute;
height: 100%;
width: 0.0625rem;
bottom: 0;
left: 0;
visibility: hidden;
-webkit-transform: scaleY(0);
transform: scaleY(0);
-webkit-transition: all .3s ease-in-out;
transition: all .3s ease-in-out;
}
#new-quote:hover:before {
visibility: visible;
-webkit-transform: scaleY(1);
transform: scaleY(1);
}
footer {
font-size: 0.85rem;
margin-bottom: 1rem;
}
footer a {
text-decoration: none;
color: #fff;
position: relative;
}
footer a:before {
content: "";
position: absolute;
width: 100%;
height: .0625rem;
bottom: 0;
left: 0;
background: #fff;
visibility: hidden;
-webkit-transform: scaleX(0);
transform: scaleX(0);
-webkit-transition: all .3s ease-in-out 0s;
transition: all .3s ease-in-out 0s;
}
footer a:hover:before {
visibility: visible;
-webkit-transform: scaleX(1);
transform: scaleX(1);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="v-wrap">
<div class="quote-container" style="">
<div class="quote-text">
</div>
<div class="quote-author"></div>
<a id="tweet-quote" class="button"><i class="fa fa-twitter"></i></a>
<a id="tumblr-quote" class="button"><i class="fa fa-tumblr"></i></a>
</div>
<div id="new-quote" class="button">New quote</div>
<footer>
Created by LukasLSC
</footer>
</div>
Code output:
As you can see, ajax wasn't success
Uncaught TypeError: callback is not a function and Uncaught TypeError: Cannot read property 'text' of undefined (only in the stack snippet).
I found out this error disappears if I remove the getQuote(); function call. However, I need to call it, overwise, my project won't work. I also tried to use return $.ajax but there was a return quote line so I couldn't use it. The full code can be found here on codepen: https://codepen.io/Kestis500/pen/ZvyxKB?editors=0110.
Then I switched to another method using jQuery promises and used information in this thread: https://stackoverflow.com/a/40658281/8889739. Full code: https://codepen.io/Kestis500/pen/qpjxoq?editors=0110.
var MyFirstFunction = function() {
var getNewQuote = function(callback) {
var quote = {};
setTimeout(function() {
quote.text = 'Example';
quote.author = 'Example';
return quote;
}, 4000);
};
}
var MySecondFunction = function() {
console.log("DONE");
var getRandomColor = function() {
var colors = [
"#ff9966",
"#7f00ff",
"#396afc",
"#0cebeb",
"#06beb6",
"#642b73",
"#36d1dc",
"#cb356b",
"#3a1c71",
"#ef3b36",
"#159957",
"#000046",
"#007991",
"#56ccf2",
"#f2994a",
"#e44d26",
"#4ac29a",
"#f7971e",
"#34e89e",
"#6190e8",
"#3494e6",
"#ee0979"
],
randomNumber = Math.floor(Math.random() * colors.length);
return colors[randomNumber];
};
var updateText = function($t, qt) {
var twitter = "https://twitter.com/intent/tweet?hashtags=quotes&related=freecodecamp&text=";
twitter += '"' + qt.text + '" ';
twitter += qt.author;
var tumblr = "https://www.tumblr.com/widgets/share/tool?posttype=quote&tags=quotes,freecodecamp&caption=";
tumblr += qt.author;
tumblr += "&content=";
tumblr += qt.text;
tumblr += "&canonicalUrl=https%3A%2F%2Fwww.tumblr.com%2Fbuttons&shareSource=tumblr_share_button";
var $icon = $("<i class='fa fa-quote-left'>")
.prop("aria-hidden", true);
$t.find(".quote-text").html("").append($icon, qt.text);
$t.find(".quote-author").html("- " + qt.author);
$("#tweet-quote").attr("href", twitter);
$("#tumblr-quote").attr("href", tumblr);
};
var calcNewHeight = function(q) {
var $temp = $("<div>", {
class: "quote-container temp",
}).appendTo($("body"));
$temp.append($("<div>", {
class: "quote-text"
}), $("<div>", {
class: "quote-author"
}));
updateText($temp, q);
var h = $temp.height() + 40;
$temp.remove();
return h;
};
var changeColor = function(newColor) {
$("body, .button:not(#new-quote)").animate({
backgroundColor: newColor
});
$("#new-quote").animate({
color: newColor
});
$(".quote-text, .quote-author").css("color", newColor);
if ($("#modStyle").length === 0) {
$("head").append(
"<style id='modStyle'>#new-quote:before {background:" + newColor + ";}</style>"
);
} else {
$("head style#modStyle").html("#new-quote:before {background:" + newColor + ";}");
}
};
var getQuote = function() {
var nq, nc, nh = 0;
nq = getNewQuote();
nc = getRandomColor();
nh = calcNewHeight(nq);
$(".quote-container").children().css("opacity", 0);
changeColor(nc);
$(".quote-container, #new-quote").animate({
height: nh,
}, {
duration: 1000,
queue: false
});
$(".quote-container").animate({
padding: "2.5em"
}, {
duration: 1000,
queue: false
});
$("#new-quote").animate({
padding: "2.5em .75em"
}, {
duration: 1000,
queue: false
});
updateText($(".quote-container"), nq);
$(".quote-container").children().fadeTo(750, 1);
};
$("#new-quote").on("click", getQuote);
$(".quote-container, #new-quote").css({
visibility: "visible",
height: 0
});
$("#new-quote").css("padding", "0 .75em");
getQuote();
}
MyFirstFunction().done(MySecondFunction);
html,
body {
height: 100%;
width: 100%;
}
body {
margin: 0;
padding: 0;
background: #333;
color: #333;
font-family: sans-serif;
}
.v-wrap {
height: 100%;
text-align: center;
}
.v-wrap:before {
content: "";
display: inline-block;
vertical-align: middle;
width: 0;
height: 100%;
}
.quote-container {
width: 31.25rem;
background: #fff;
margin: 0;
display: inline-block;
vertical-align: middle;
border-radius: 0.1875rem;
border-top-right-radius: 0;
border-bottom-right-radius: 0;
visibility: hidden;
padding: 0 2.5rem;
}
.quote-text {
font-size: 1.625rem;
}
.quote-text i {
margin-right: 0.6rem;
}
.quote-text p {
display: inline;
}
.quote-author {
font-size: 1rem;
margin: 0 0.4rem 2rem 0;
text-align: right;
}
.button {
padding: 0.75rem;
text-align: center;
font-size: 1rem;
color: #fff;
border-radius: .1875rem;
display: inline-block;
cursor: pointer;
-webkit-user-select: none;
user-select: none;
}
.button:not(#new-quote):hover {
opacity: .8 !important;
}
.button:not(#new-quote) {
min-width: 1rem;
min-height: 1rem;
}
.button i {
vertical-align: middle;
}
#new-quote {
white-space: nowrap;
writing-mode: vertical-lr;
height: 50%;
border-top-left-radius: 0;
border-bottom-left-radius: 0;
vertical-align: middle;
background: #fff !important;
margin: 0;
position: relative;
right: 0.25625rem;
color: #333;
visibility: hidden;
}
#new-quote:before {
content: "";
position: absolute;
height: 100%;
width: 0.0625rem;
bottom: 0;
left: 0;
visibility: hidden;
-webkit-transform: scaleY(0);
transform: scaleY(0);
-webkit-transition: all .3s ease-in-out;
transition: all .3s ease-in-out;
}
#new-quote:hover:before {
visibility: visible;
-webkit-transform: scaleY(1);
transform: scaleY(1);
}
footer {
font-size: 0.85rem;
margin-bottom: 1rem;
}
footer a {
text-decoration: none;
color: #fff;
position: relative;
}
footer a:before {
content: "";
position: absolute;
width: 100%;
height: .0625rem;
bottom: 0;
left: 0;
background: #fff;
visibility: hidden;
-webkit-transform: scaleX(0);
transform: scaleX(0);
-webkit-transition: all .3s ease-in-out 0s;
transition: all .3s ease-in-out 0s;
}
footer a:hover:before {
visibility: visible;
-webkit-transform: scaleX(1);
transform: scaleX(1);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="v-wrap">
<div class="quote-container" style="">
<div class="quote-text">
</div>
<div class="quote-author"></div>
<a id="tweet-quote" class="button"><i class="fa fa-twitter"></i></a>
<a id="tumblr-quote" class="button"><i class="fa fa-tumblr"></i></a>
</div>
<div id="new-quote" class="button">New quote</div>
<footer>
Created by LukasLSC
</footer>
</div>
Code output:
It broke everything, the gray screen is because of the default codepen background
Uncaught TypeError: Cannot read property 'done' of undefined
You're using return from the asynchronous operation's callback. That just sets the return value of that callback (which is ignored in the case of setTimeout's or XHR's callback), it doesn't set the return value of your function.
You can't return the value from your function, which is why you're adding a callback. Instead:
var getNewQuote = function(callback) {
var quote = {};
setTimeout(function() {
quote.text = 'Example';
quote.author = 'Example';
callback(quote); // <====
}, 4000);
};
...and use the parameter of the callback, e.g.:
getNewQuote(function(quote) {
// Use quote here...
});
Live Example:
var getNewQuote = function(callback) {
var quote = {};
setTimeout(function() {
quote.text = 'Example';
quote.author = 'Example';
callback(quote); // <====
}, 1000);
};
getNewQuote(function(quote) {
console.log("quote:", quote);
});

for/if loop to run a function multiple times depending on input :: jquery

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');

Categories