I have a simple animation on my page that cycles through quotes (from a javascript array, currently). Before a new quote is loaded, jQuery moves the div to the right a bit and hides it. Then it loads the new text and moves the div back to the left while fading it in.
Here is the
JavaScript:
var lastIndex;
$(document).ready(function () {
cycleTestimonial(); // set first testimonial
setInterval(cycleTestimonial, 9000); // cycle through testimonials every x seconds after that
});
function cycleTestimonial() {
var testi = getTestimonial(); // retrieve testimonial
if (!testi) return; // usually means duplicate of last quote, so skip setting HTML
$('#testimonial').hide(0, function () { // erase current quote
$('#testimonial > #quote').html(testi['quote'].replace(/'/g, "’"));
$('#testimonial > #author').html(testi['auth']);
$('#testimonial > #tagline').html(testi['tag']);
$(this).velocity({ // set opacity to 0 and move right instantaneously to prepare to fade new quote in
right: '-=60',
opacity: 0.0
}, 0, function () {
var testiH = $(this).height();
var headH = $('#home-header').height() / 2;
$(this).offset({ 'top': (headH-(testiH/2)) });
$(this).show().velocity({ // fade in new quote and slide left
right: '+=60',
opacity: 1.0
}, 600);
});
});
}
function getTestimonial(index) {
var t = [ { "quote" : "I love this product.",
"auth" : "John Doe",
"tag" : "Preferred Client"
},
...
];
if (!index) { // no specific testimonial asked for, get a random one
index = Math.floor(Math.random() * t.length);
if (index == lastIndex) { // retrieved same testimonial as last time
cycleTestimonial(); // re-run until we get a new testimonial from last time
return;
}
else lastIndex = index; // set to ensure no repeats back-to-back
}
return t[index];
}
For thoroughness, here is the corresponding
HTML:
<div id="home-header">
<div class="boundary">
<div id="testimonial">
<div id="quote">
quote
</div>
<div id="author">
author
</div>
<div id="tagline">
tagline
</div>
</div>
</div>
</div>
And, finally, relevant
CSS:
.boundary {
display: block;
position: relative;
margin: 0 auto;
max-width: 1080px;
min-width: 720px;
height: inherit;
}
#home-header {
display: block;
position: relative;
height: 420px;
width: inherit;
}
#home-header #testimonial {
position: absolute;
display: block;
top: 40px;
right: 0px;
min-width: 350px;
max-width: 470px;
}
#home-header #testimonial #quote {
display: block;
width: inherit;
text-align: left;
font-size: 26pt;
font-style: italic;
line-height: 1.2;
color: #0085df;
font-weight: 300;
}
#home-header #testimonial #author {
display: block;
width: inherit;
text-align: right;
font-size: 14pt;
font-weight: 700;
color: #999;
}
#home-header #testimonial #tagline {
display: block;
width: inherit;
text-align: right;
text-transform: uppercase;
font-weight: 400;
font-size: 8pt;
color: #999;
}
Now, this code works great most of the time. However, when I switch away from the page to a different tab or window, and then come back to it, the alignment is all screwy until a new quote is loaded.
Also, when I load the page, occasionally the alignment gets screwed up then too, like it was placed before the page was fully loaded or loaded enough for it to place properly.
Is there a better way to do what I'm doing that won't come with these issues on placement?
Related
I am using the distance of the the span from the top to position the caret vertically, that works fine, and I am using the index of the string multiplied by the letter width to position the caret horizontally but that sometimes works, sometimes it doesn't.
Look for example at the second row, and click in the first "this", it doesn't work properly but if you click inside the last "this" the caret gets positioned correctly.
I can't figure out why, doesn't it mean that a mono-space font has the exact same with for each letter which I eyeballed here to be 10.1? Something doesn't work here and I can't figure out what. JsFiddle
let writeDiv = document.querySelector('#write');
let caret = document.querySelector('#caret')
writeDiv.addEventListener('click', (e) => {
if(e.target.tagName == 'SPAN'){
moveCaretOnClick(e)
}
})
function moveCaretOnClick(e) {
let y = window.getSelection().focusOffset * 10.1
caret.style = `left: ${y}px; top: ${e.target.offsetTop + 3}px`;
}
#import url('https://fonts.googleapis.com/css2?family=Roboto+Mono&display=swap');
body, html{
margin: 0;
height: 100%;
width: 100%;
}
#write {
font-family: 'Roboto Mono';
height: 100%;
width: 100%;
background: #1f2227;
padding: 10px;
color: white;
box-sizing: border-box;
}
#caret{
height: 15px;
width: 3px;
background: #80ff00;
display: inline-block;
position: absolute;
}
.RowSpan{
width: 100%;
display: inline-block;
box-sizing: border-box;
height: 20px;
}
<div id='write'>
<span class='RowSpan'>This is some text</span>
<span class='RowSpan'>this is some text this</span>
</div>
<div id='caret'></div>
Edit: My guess is that I need the exact dimension of the letters, otherwise, as you go further the line the distance increases more and more, because of multiplying for each letter. If you add more text the distance gets more and more further from the click.
So, somehow either get the exact dimension of the letters that's always consistent or find some other way.
A bit awkward but I fount the solution, it turns out I just had to add a 1 to the focusOffset before multiplying with each letter, otherwise it would basically skip a letter. I think because focusOffset starts with a 0
let writeDiv = document.querySelector('#write');
let caret = document.querySelector('#caret')
writeDiv.addEventListener('click', (e) => {
if(e.target.tagName == 'SPAN'){
moveCaretOnClick(e)
}
})
function moveCaretOnClick(e) {
let y = (window.getSelection().focusOffset + 1) * 9.6
caret.style = `left: ${y}px; top: ${e.target.offsetTop + 3}px`;
}
#import url('https://fonts.googleapis.com/css2?family=Roboto+Mono&display=swap');
body{
margin: 0;
}
#write {
font-family: 'Roboto Mono';
height: 300px;
width: 1200px;
background: #1f2227;
padding: 10px;
color: white;
}
#caret{
height: 15px;
width: 2px;
background: #80ff00;
display: inline-block;
position: absolute;
}
.RowSpan{
width: 100%;
display: inline-block;
box-sizing: border-box;
height: 20px;
}
<div id='write'>
<span class='RowSpan'>This is some text</span>
<span class='RowSpan'>this is some text this more more text BIGGERT TEXT and some small text and some stuff -- __ !%^ () {} and some more text even </span>
</div>
<div id='caret'></div>
var cancelBtn = document.querySelector(".btn--cancel");
var acceptBtn = document.querySelector(".btn--accept");
var thankYouPopup = document.querySelector(".thank-you-popup");
var comeBackSoonPopup = document.querySelector(".come-back-soon-popup");
document.addEventListener(
"click",
function(e) {
if (
((e.target.className !== "btn btn--cancel" ||
e.target.className !== "btn btn--accept") &&
e.target.className == "btn-container") ||
(e.target.className !== "thank-you-popup" &&
e.target.className == "thank-you-container") ||
(e.target.className !== "come-back-soon-popup" &&
e.target.className == "come-back-soon-container")
) {
console.log("foo");
var els = document.querySelectorAll("*");
for (let i = 0; i < els.length; i++) {
console.log("els[i]", els[i]);
if (
els[i].left === "0" &&
(els[i].className === "thank-you-popup" ||
els[i].className === "come-back-soon-popup")
) {
setTimeout(function() {
els[i].style.left = "10000px";
}, 0);
}
}
}
},
false
);
function myEventHandler(el) {
if (getComputedStyle(el).left == "10000px") {
el.style.left = "0";
setTimeout(function() {
el.style.left = "10000px";
}, 8000);
} else {
el.style.left = "10000px";
}
}
cancelBtn.addEventListener(
"click",
function() {
myEventHandler(comeBackSoonPopup);
},
false
);
cancelBtn.removeEventListener(
"click",
function() {
myEventHandler(comeBackSoonPopup);
},
false
);
acceptBtn.addEventListener(
"click",
function() {
myEventHandler(thankYouPopup);
},
false
);
acceptBtn.removeEventListener(
"click",
function() {
myEventHandler(thankYouPopup);
},
false
);
* {
box-sizing: border-box;
}
body {
overflow-x: hidden;
}
main {
height: auto;
margin-top: 0%;
font: 1rem system-ui;
}
.thank-you-container,
.come-back-soon-container {
width: 100%;
display: flex;
justify-content: flex-end;
}
.thank-you-popup,
.come-back-soon-popup {
text-align: center;
padding: 5%;
height: 38px;
background: lightgrey;
border: 3px solid #bbb;
border-radius: 4px;
width: 50%;
display: flex;
justify-content: center;
align-items: center;
font-size: 3em;
text-shadow: 0px 1px 0px;
position: relative;
left: 10000px;
transition-property: left;
transition-duration: 1s;
}
p {
text-shadow: 0px 1px 0px rgba(255, 255, 255, 1);
}
.btn-container {
margin: 5% 0;
display: flex;
justify-content: center;
}
.btn {
display: inline-block;
margin: 0 1%;
height: 38px;
padding: 0 30px;
line-height: 38px;
color: #ffffff;
text-align: center;
font-size: 11px;
font-weight: 600;
letter-spacing: 0.1rem;
text-transform: uppercase;
text-decoration: none;
white-space: nowrap;
background-color: transparent;
border-radius: 4px;
border: 1px solid #bbb;
cursor: pointer;
-o-transition: background-color 0.225s ease-in;
transition: background-color 0.225s ease-in;
}
.btn--cancel {
background-color: #ff4136;
}
.btn--cancel:hover {
background-color: #e2392f;
}
.btn--accept {
background: #01ff70;
}
.btn--accept:hover {
background-color: #06da63;
}
<main>
<div class="thank-you-container">
<div class="thank-you-popup">
<p>Thank you!</p>
</div>
</div>
<div class="btn-container">
<button class="btn btn--cancel">cancel</button>
<button class="btn btn--accept">accept</button>
</div>
<div class="come-back-soon-container">
<div class="come-back-soon-popup">
<p>Come back soon!</p>
</div>
</div>
</main>
<!--
In this exercise, you are asked to create a couple of buttons that, when clicked, trigger the display of popups. We want to not only see your coding skills, but also your eye for design and experience. Follow the instructions below and feel free to explain what you're doing or ask questions as you go.
1. Create two buttons centered on the page, next to each other. One should be for canceling and the other for accepting, so use appropriate background colors. The buttons should have rounded borders and should brighten up a bit with easing on hover.
2. Create two popups, one positioned a bit off from the bottom right corner of the page and the other from the top right. The popups should have rounded corners, a slightly thick border, and some padding. One popup should contain the text "Thank you!" while the other should contain the text "Come back soon."
3. Now, position the two popups off screen to the right using CSS.
4. We will now complete the exercise. Add a click handler to each button. For the first button, when clicked we want to slide the "Come back soon" popup from the right into view. For the second button, when clicked we want to slide the "Thank you!" popup from the right into view. The popups should slide back out of view 8 seconds after coming into view or when clicking anywhere on the page except the buttons and the popups.
5. BONUS: Make this work for touch devices!
-->
I'm close to fulfilling this requirement in an exercise:
We will now complete the exercise. Add a click handler to each button.
For the first button, when clicked we want to slide the "Come back
soon" popup from the right into view. For the second button, when
clicked we want to slide the "Thank you!" popup from the right into
view. The popups should slide back out of view 8 seconds after coming
into view or when clicking anywhere on the page except the buttons and
the popups.
I decided to isolate this eventListener on the document to loop only elements in the DOM but when I console.log it's spitting out every possible node i.e. blank spaces, css, script tags.
Can anyone help me just isolate the elements in the dom?
I have included a working example, HTML, CSS and JavaScript
Thanks in advance!
Is this what you want?
var els = document.querySelectorAll("body *");
I've tried to look for a solution for this but have failed miserably. It's my first ever time using JS (I'm trying to learn) so the possibility of my just not understanding the answers in the search results properly is quite high - sorry about that.
I am wanting a JS carousel, generated from an array, with Prev/Next buttons (ideally responsive etc but that'll come at a later stage), preferably with captions underneath. I can get the carousel to work but I end up getting a text link when I click on either Prev or Next. And I've no idea how to add the caption array underneath (I've taken out the JS for the captions for now because it was messing everything else up even further).
Relevant HTML:
<body onload="changePilt()">
<span id="prev" class="arrow">❮</span>
<div class="karussell" id="karussell">
<img class="karu" name="esislaid">
</div>
<span id="next" class="arrow">❯</span>
<div class="caption">
<h3 name="esikiri"></h3>
</div>
</body>
CSS, just in case:
.karussell {
position: relative;
width: 100%;
max-height: 600px;
overflow: hidden;
}
.arrow {
cursor: pointer;
position: absolute;
top: 40%;
width: auto;
color: #00A7E0;
margin-top: -22px;
padding: 16px;
font-weight: bold;
font-size: 18px;
transition: 0.6s ease;
border-radius: 0 3px 3px 0;
}
#next {
right: 0;
border-radius: 3px 0 0 3px;
}
#prev {
left: 0;
}
.arrow:hover {
background-color: rgba(0,0,0,0.8);
}
.caption {
text-align: center;
color: #00A7E0;
padding: 2px 16px;
}
.karu {
max-width: 75%;
}
#media (max-width:767px){.karu{max-width: 95%;}}
And finally, the dreaded JS:
var i = 0;
var s = 0;
var esileht = [];
var aeg = 5000;
//Image List
esileht[0] = 'img/tooted/raamat/graafvanalinn2016.jpg';
esileht[1] = 'img/tooted/kaart/kaart_taskus_esipool.jpg';
esileht[2] = 'img/tooted/kaart/graafkaart_esikylg.jpg';
//Change Image
function changePilt (){
document.esislaid.src = esileht[i];
if(i < esileht.length -1){
i++;
} else {
i = 0;
}
setTimeout("changePilt()", aeg);
}
document.onload = function() {
}
// Left and Right arrows
//J2rgmine
function jargmine(){
s = s + 1;
s = s % esileht.length;
return esileht [s];
}
//Eelmine
function eelmine(){
if (s === 0) {
s = esileht.length;
}
s = s -1;
return esileht[s];
}
document.getElementById('prev').addEventListener('click', function (e){
document.getElementById('karussell').innerHTML = eelmine();
}
);
document.getElementById('next').addEventListener('click', function (e) {
document.getElementById('karussell').innerHTML = jargmine();
}
);
I'm sure the solution is dreadfully obvious, I just cannot seem to be able to figure it out...
instead of innerHTML change src attribute of image
document.querySelector('#karussell img').src = eelmine();
And
document.querySelector('#karussell img').src = jargmine();
My web application has a listener for barcode scans. How I got that working is another story.
Anyhow, I need to be able to alert the user when a scan is detected and if the back-end processing that ingested that scan was successful.
To help with that I have taken 2 divs and overlaid them.
The bottom div has some text that says "Ready To Scan" and the top div has some text that describes that status of the last scan. So basically, the way this will work, the user will "scan" something and then the div will display 100% of it's width some message that says "OK" or "Stop!" or "Do something..." depending on some business logic. But about 2-3 seconds later I want that div to slide to the left exposing the bottom div that says "Ready to scan". That way the user can continue scanning and they are aware that their last scan was "accepted."
Here is the code. To get the div to slide - hit the space bar.:
var counter = 0;
window.onkeyup = function(e) {
var key = e.keyCode ? e.keyCode : e.which;
if (key == 32) {
if (counter == 0) {
slide();
}
}
}
function slide() {
var $lefty = $('#scanner-status-error');
var $percentage = $lefty.outerWidth() - ($lefty.outerWidth() * .15);
$lefty.animate({
left: parseInt($lefty.css('left'),10) == 0 ?
-$percentage : 0
});
}
#scanner-status {
position: relative;
}
#scanner-status img {
display: inline-block;
max-width: 15px;
margin-right: 3px;
}
#scanner-status-ready {
top: 0;
left: 0;
width: 100%;
position: absolute;
vertical-align: middle;
text-align: center;
background-color: #939598;
max-height: 28px;
font-family: "Times New Roman", Times, serif;
font-weight: bold;
}
#scanner-status-error {
top: 0;
left: 0;
width: 100%;
position: absolute;
vertical-align: middle;
text-align: center;
background-color: #e54a5c;
max-height: 28px;
font-family: "Times New Roman", Times, serif;
color: white;
font-weight: bold;
z-index: 10;
}
.scanner-status-message {
display: inline-block;
line-height: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="scanner-status">
<div id="scanner-status-error">
<div class="scanner-status-message">Stop!</div>
</div>
<div id="scanner-status-ready">
<div class="scanner-status-message">Ready to Scan</div>
</div>
</div>
Question / Problem: I'm using JQuery to do the animation and my text is centered in the top div. The problem I'm running into is that as my div moves to the left of the screen, the div isn't shrinking in size, but just moving to the left, thus the centered text is no longer seen. How do I adjust for the moving div but at the same time ensure that my text is "centered"?
You were animating the left property instead of the width property.
var counter = 0;
window.onkeyup = function(e) {
var key = e.keyCode ? e.keyCode : e.which;
if (key == 32) {
if (counter == 0) {
slide();
}
}
}
function slide() {
var $lefty = $('#scanner-status-error');
var $percentage = $lefty.outerWidth() - ($lefty.outerWidth() * .15);
$lefty.animate({
width: "40"
});
}
#scanner-status {
position: relative;
}
#scanner-status img {
display: inline-block;
max-width: 15px;
margin-right: 3px;
}
#scanner-status-ready {
top: 0;
left: 0;
width: 100%;
position: absolute;
vertical-align: middle;
text-align: center;
background-color: #939598;
max-height: 28px;
font-family: "Times New Roman", Times, serif;
font-weight: bold;
}
#scanner-status-error {
top: 0;
left: 0;
width: 100%;
position: absolute;
vertical-align: middle;
text-align: center;
background-color: #e54a5c;
max-height: 28px;
font-family: "Times New Roman", Times, serif;
color: white;
font-weight: bold;
z-index: 10;
}
.scanner-status-message {
display: inline-block;
line-height: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="scanner-status">
<div id="scanner-status-error">
<div class="scanner-status-message">Stop!</div>
</div>
<div id="scanner-status-ready">
<div class="scanner-status-message">Ready to Scan</div>
</div>
</div>
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');