How to make images change automatically - javascript

I am new to javascript and I am trying to do a featured content slider something like the top banner in this website http://www.homeplus.co.kr
As you can see, the top big banner changes automatically & also will change when user hovers over one of the list at the right.
Right now I am able to do the hovering part, but I am still stuck at the automatic changing content part.
Here's a sample jsfiddle: http://jsfiddle.net/StormSdq/5tWPy/2/
<div class="pi">a</div>
<div class="pi">b</div>
<div class="pi">c</div>
<div class="pi">d</div>
<div class="c1">I DREAM</div>
<div class="c1">OF LLAMAS</div>
<div class="c1">JUMPING AROUND</div>
<div class="c1">EATING BUSHES</div>
css:
.pi {
font-size:12px;
color:#000;
font-weight:700;
width:30px;
height:25px;
margin-right:10px;
background:transparent;
border-bottom:solid 1px black;
}
.c1 {
border:1px solid blue;
background:lightskyblue;
width:200px;
height:200px;
float:right;
margin-right:430px;
margin-top:-100px;
color:red;
font-size:25px;
text-align:center;
display:none;
}
javascript:
div = document.getElementsByClassName('c1');
div[0].style.display = 'block'
B = document.getElementsByClassName('pi');
B[0].onmouseover = function () {
blip(0);
};
B[1].onmouseover = function () {
blip(1);
};
B[2].onmouseover = function () {
blip(2);
};
B[3].onmouseover = function () {
blip(3);
};
function blip(y) {
div = document.getElementsByClassName('c1');
for (x = 0; x < (div.length); x++) {
div[x].style.display = 'none';
}
div[y].style.display = 'block';
}
Any help will be greatly appreciated

Try this:
var cur = 0; // current index
setInterval(autoAnim, 2000); // auto change every 2s
function autoAnim(){
if(cur > 3) cur = 0;
blip(cur);
cur++;
}
Here is jsfiddle

You can use the function setTimeout to call something after XX miliseconds.
var number=0;
setTimeout(automatic,5000); // every 5 seconds
function automatic(){
blip(number);
number++;
if (number > 4)
number=0;
alert("Hello");
setTimeout(automatic,5000);
}
You will probably want to make the function sleep when mouse is hover and some others condtions

Related

Building a jquery/javascript HIIT with autoplay video or image slider "playlist" using and php/mysql

I am trying to create a countdown timer with videos. The timer needs to load data such as time for countdown, time for breaks, and number of sets the timers needs to run, video(or images in case of no video) from a MySQL table.
The timer starts counting down but needs also to start auto-playing video of image slider. When time ends starts counting down for the time break. This process continues till number of sets reached. Then it is needed to either click to go to the next countdown or after a short countdown break to load the next in queue.
I can load the data from MySQL with php and create a while loop to pass the variables need in the jQuery/JavaScript script. But i am not sure if this is the right way.
This is my approach with a bug related on clicking start/stop/reset buttons which leads to an increase of speed during countdown, and in some unwanted results regarding counting down.
A fix on that bug would be appreciated.
My code:
var startTime = 10;
var restTime = 5;
var currentTime = 0;
var myTimer;
var myTimerSpeed = 1000; // 1 sec
var currentSet = 0;
var currentPause = 0;
var totalSets = 5;
resetTimer();
restTimer();
$('#pause').hide();
$('#next_exe').hide();
$('#player').show();
$('input[value="start"]').click(startTimer);
$('input[value="stop"]').click(stopTimer);
$('input[value="reset"]').click(resetTimer);
$('#currentset').html(currentSet);
$('#totalset').html(totalSets);
$('#currentpause').html(currentPause);
$('#totalpause').html(totalSets);
function resetTimer() {
stopTimer();
currentTime = startTime;
$('#timer').html(currentTime);
}
function startTimer() {
currentSet++;
if (currentTime <= 0) {
//resetTimer();
startTimer();
} else {
myTimer = setInterval(timerTick, myTimerSpeed);
}
$('#currentset').html(currentSet);
}
function restTimer() {
stopTimer();
currentTime = restTime;
$('#timer').html(currentTime);
}
function breakTimer() {
currentPause++;
if (currentTime <= 0) {
restTimer();
breakTimer();
} else {
myTimer = setInterval(timerTick, myTimerSpeed);
}
$('#currentpause').html(currentPause);
}
function timerTick() {
currentTime--;
if (currentTime == 0 && currentSet == totalSets) {
if (currentPause < totalSets && currentPause < currentSet) {
restTimer();
breakTimer();
$('#pause').show();
$('#player').hide();
$('#next_exe').hide();
} else {
stopTimer();
//$('#myTimer').hide();
$('#next_exe').show();
$('#pause').hide();
$('#player').hide();
}
} else if (currentTime == 0 && currentSet < totalSets) {
if (currentPause < totalSets && currentPause < currentSet) {
restTimer();
breakTimer();
$('#pause').show();
$('#player').hide();
} else {
resetTimer();
startTimer();
$('#pause').hide();
$('#player').show();
}
}
$('#timer').html(currentTime);
$('#currentset').html(currentSet);
$('#currentpause').html(currentPause);
}
function stopTimer() {
clearInterval(myTimer);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>
I want to create 2 countdowns, which can loop everytime countdown ends and a set is completed.
</p>
<div id="myTimer" style="background-color:#eee; clear:both; display:block; float:left; height:250px; width:300px; margin:0; padding:20px;">
<div id="player" style="background-color:#333; color:#fff; font-size:14pt; clear:both; display:block; float:left; height:150px; width:300px; margin:0; padding:0;">
<!-- embed for youtube video https://www.youtube.com/watch?v=NlOF03DUoWc -->
<iframe width="100%" height="150" src="http://www.youtube.com/embed/gmRTQfLrbMY" frameborder="0" allowfullscreen></iframe>
</div>
<div id="pause" style="background-color:#333; color:#fff; font-size:14pt; clear:both; display:block; float:left; height:50px; width:300px; margin:0; padding:50px 0;">
PAUSE
</div>
<div id="next_exe" style="background-color:#333; color:#fff; font-size:14pt; clear:both; display:block; float:left; height:50px; width:300px; margin:0; padding:50px 0;">
Next Exercise
</div>
<p id='timer'></p>
<input type="button" value="stop">
<input type="button" value="start">
<input type="button" value="reset">
</div>
<div id="sets" style="background-color:#eee; clear:both; display:block; float:left; height:50px; width:300px; margin:10px 0 0; padding:20px;">
Number of Sets completed: <span id="currentset"></span> / <span id="totalset"></span>
<br> Number of Breaks completed: <span id="currentpause"></span> / <span id="totalpause"></span>
</div>
Also available on JSfiddle
Suggestion of a friend:
$('#pause').hide();
$('#player').hide();
$('#next_exe').hide();
function Timer(speed, duration, onTick, onComplete) {
var speed = speed;
var interval = null;
var current = duration;
var onTick = (typeof onTick == 'function') ? onTick : function() {}
var onComplete = (typeof onComplete == 'function') ? onComplete : function() {}
function decrement() {
onTick(current);
if (current > 0) {
current -= 1;
} else {
stop();
onComplete();
}
}
function start() {
if (!interval) {
interval = window.setInterval(decrement, speed);
}
}
function stop() {
if (interval) {
interval = window.clearInterval(interval);
}
}
function reset() {
current = duration;
onTick(current);
}
return {
start: start,
stop: stop,
reset: reset
};
}
function RoundCounter() {
var currentSet = 0;
var totalSets = 2;
var currentPause = 0;
var totalPause = 2;
var currentTimer = null;
var mode = null;
function initialize() {
mode = "set";
currentTimer = Timer(1000, 10, timerTick, completeSet);
setupUI();
bindUIEvents();
}
function setupUI() {
$('#totalset').html(totalSets);
$('#totalpause').html(totalPause);
$('#currentset').html(currentSet);
$('#currentpause').html(currentPause);
}
function bindUIEvents() {
$('input[value="start"]').click(function() {
runTimer(currentTimer);
$('#pause').hide();
$('#player').show();
$('#next_exe').hide();
});
$('input[value="stop"]').click(function() {
stopTimer(currentTimer);
});
$('input[value="reset"]').click(function() {
resetTimer(currentTimer);
});
$('#sets')
.on("timerset.complete", function() {
updateUI();
})
.on("timerpause.complete", function() {
updateUI();
});
}
function updateUI() {
$('#currentset').html(currentSet);
$('#currentpause').html(currentPause);
if (currentPause == totalPause &&
currentSet == totalSets) {
endRound();
return;
}
if (mode == "set") {
$('#pause').hide();
$('#player').show();
$('#next_exe').hide();
if (currentPause < totalPause) {
currentTimer = Timer(1000, 5, timerTick, completePause);
runTimer(currentTimer);
}
mode = "pause";
} else if (mode == "pause") {
$('#pause').show();
$('#player').hide();
$('#next_exe').hide();
if (currentSet < totalSets) {
currentTimer = Timer(1000, 10, timerTick, completeSet);
runTimer(currentTimer);
}
mode = "set";
}
}
function startNextTimer() {
if (mode == "set") {}
}
function timerTick(currentTime) {
$('#timer').html(currentTime);
}
function runTimer(timer) {
timer.start();
}
function stopTimer(timer) {
timer.stop();
}
function resetTimer(timer) {
timer.reset();
}
function completeSet() {
currentSet += 1;
$("#sets").trigger("timerset.complete");
$('#pause').show();
$('#player').hide();
$('#next_exe').hide();
}
function completePause() {
currentPause += 1;
$("#sets").trigger("timerpause.complete");
$('#pause').hide();
$('#player').show();
$('#next_exe').hide();
}
function endRound() {
$('#myTimer').hide();
$('#sets')
.off('timerset.complete')
.off('timerpause.complete');
}
return {
initialize: initialize
};
}
// on document ready, initialize everything
$(function() {
RoundCounter().initialize();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>
I want to create 2 countdowns, which can alter everytime countdown ends and a set is completed.
</p>
<div id="myTimer" style="background-color:#eee; clear:both; display:block; float:left; height:auto; width:300px; margin:0; padding:20px;">
<div id="player" style="background-color:#333; color:#fff; font-size:12pt; clear:both; display:block; float:left; height:180px; width:300px; margin:0 0 20px; padding:0;">
<!-- embed for youtube video https://www.youtube.com/watch?v=NlOF03DUoWc -->
<iframe width="100%" height="150" src="http://www.youtube.com/embed/gmRTQfLrbMY" frameborder="0" allowfullscreen></iframe> VIDEO or Image Slider
</div>
<div id="pause" style="background-color:#333; color:#fff; font-size:12pt; clear:both; display:block; float:left; height:80px; width:280px; margin:0 0 20px; padding:50px 10px;">
PAUSE
</div>
<div id="next_exe" style="background-color:#333; color:#fff; font-size:12pt; clear:both; display:block; float:left; height:80px; width:280px; margin:0 0 20px; padding:50px 10px;">
go to next exercise
</div>
<p id='timer'></p>
<input type="button" value="stop">
<input type="button" value="start">
<input type="button" value="reset">
</div>
<div id="sets" style="background-color:#eee; clear:both; display:block; float:left; height:50px; width:300px; margin:10px 0 0; padding:20px;">
Number of Sets completed: <span id="currentset"></span> / <span id="totalset"></span>
<br> Number of Breaks completed: <span id="currentpause"></span> / <span id="totalpause"></span>
</div>
This is also available on JSfiddle
Your timer issue comes from these lines of code:
myTimer = setInterval(timerTick, myTimerSpeed);
An interval is not really a variable, when you call setInterval you are creating an interval and getting in return a reference to that interval.
So if the code above is called twice, you'll have 2 intervals running but only a reference to the 2nd one, which means it will run forever and you no longer have the value needed to stop the first one.
What your friend did is to ensure there was no running interval referenced by his variable before starting a new one.
You can achieve the same result by replacing the lines above with:
if(myTimer) clearInterval(myTimer);
myTimer = setInterval(timerTick, myTimerSpeed);
And adding an initial value to your timer with var myTimer = false;. That should fix your timer issues
To fix transitions, I basically removed their logic from the timers start/stop functions. All transitions are now handled by timerTick().
I added a isBreak variable to remember if we're currently in a break or set, which is then used to determine what step is next and what timer initial value to fetch.
I included two reset functions in the code (resetAll() & resetCurrent()), since I didn't know if you wanted to reset everything or only the current timer.
It should now work as follow: set -> break (5x) and on the last break, instead of PAUSE it displays Next Exercise (to which you can add a click listener calling loadNext() if you want the user to be able to start it manually).
In loadNext() you can load the images for the next exercise, and if you uncomment startTimer() it will start right away.
Result: Fiddle
Does that work as you wanted it to?

Element won't show() according to variable value and if statement

I am trying to make a blue square show if fullScreenCropStatus = true and a red square show if fullScreenCropStatus = false once the 'Done' button is clicked.
The variable is correct and is showing the correct value, but the blue square does not show when 'Done' is clicked. I tried show()/hide() and also the current format of setting the display value in css but neither make the blue square appear.
The red square successfully hide() or display:none. I am really baffled on this.
The code is below and this is the JSbin
JS:
var fullScreenCrop = false;
var fullScreenCropStatus = false;
$('#cropping--modes').click(function() {
fullScreenCrop = !fullScreenCrop;
console.log("fullScreenCrop = " + fullScreenCrop);
});
$("#done").click(function() {
fullScreenCropStatus = fullScreenCrop;
console.log("fullScreenCropStatus = " + fullScreenCropStatus);
if (fullScreenCropStatus === true) {
$(".done--title__container").css("display", "none");
$(".done--title__container--fullscreen").css("display", "block");
} else if (fullScreenCropStatus === false) {
$(".done--title__container").css("display", "block");
$(".done--title__container--fullscreen").css("display", "none");
}
});
HTML:
<button id="cropping--modes">Toggle variable (true/false)</button>
<button id="done">Done</button>
<div class="done--title__container">
<div class="done--title__container--fullscreen">
CSS:
.done--title__container { display:none; width:50px; height:50px; background-color:red; position:relative; }
.done--title__container--fullscreen { display:none;width:50px; height:50px; background-color:blue; position:relative; }
#cropping--modes { display:block; width:200px; height:30px; }
#done { display:block; width:200px; height:30px; }
Close the div tags and you're fine:
<button id="cropping--modes">Toggle variable (true/false)</button>
<button id="done">Done</button>
<div class="done--title__container"></div>
<div class="done--title__container--fullscreen"></div>

How to change an HTML class with JavaScript using getElementsByClassName [duplicate]

This question already has answers here:
How to add/remove a class in JavaScript?
(13 answers)
Closed 5 years ago.
How to change a class with Javascript using getElementsByClassName. I got it to work a little but it won't change the class one at the time bet only do it one time to.
I click the button to change css class it do it on all the div and I can do it more in one time.
Here is my Code
function Button_Color(Show_This) {
var x = document.getElementById("Color_box");
var i;
var Show_This;
if (Show_This == 1)
{
var d = document.getElementsByClassName("id_blue");
d[0].className = "hid";
var o = document.getElementsByClassName("id_red");
o[0].className = " uhid";
}
if (Show_This == 2) {
var d = document.getElementsByClassName("id_blue");
d[0].className = "hid";
var o = document.getElementsByClassName("id_red");
o[0].className = " uhid";
}
}
Here is a like to show you how it looks now with html css js
https://jsfiddle.net/ee51o5h5/1/
I want it to show red only when you click the little red one and blue only when you click the little blue one.
i am dyslexic and from a non-english speaking country so sorry for any miss up.
i try this :
<body>
<section class="section-button-box">
<div class="box-button box-color01" onClick="Button_Color(1);">
</div>
<div class="box-button box-color02" onClick="Button_Color(2);">
</div>
</section>
<section class="section-color-box" id="Color_box">
<div class="main-color id_blue">
<div class="box-size box-color01">
</div>
</div>
<div class="main-color id_red">
<div class="box-size box-color02">
</div>
</div>
<div class="main-color id_blue">
<div class="box-size box-color01">
</div>
</div>
<div class="main-color id_red">
<div class="box-size box-color02">
</div>
</div>
</section>
</body>
JS:
/*| Blue box |*/
function Button_Color(Show_This) {
var x = document.getElementById("Color_box");
var i;
var Show_This;
var list = document.getElementsByClassName("main-color");
for(var i = 0 ; i < list.length; i ++ ){
if (Show_This == 1)
{
console.log(list[i].classList.contains("id_blue"));
if(list[i].classList.contains("id_blue")){
list[i].classList.add("uhid");
list[i].classList.remove("hid");
}
if(list[i].classList.contains("id_red")){
list[i].classList.add("hid");
list[i].classList.remove("uhid");
}
}
if (Show_This == 2) {
console.log(list[i].classList.contains("id_blue"));
if(list[i].classList.contains("id_blue")){
list[i].classList.add("hid");
list[i].classList.remove("uhid");
}
if(list[i].classList.contains("id_red")){
list[i].classList.add("uhid");
list[i].classList.remove("hid");
}
}
}
}
and css :
/*| Button Box |*/
.section-button-box{
height:100px;
width:100%;
background-color:aqua;
}
.box-button{
height:50px;
width:50px;
float:left;
}
/*| Color Box |*/
.section-color-box{
height:300px;
background-color:#c1c1c1;
width:100%;
}
.box-size{
height:100px;
width:100px;
float:left;
}
.box-color01{
background-color:blue;
}
.box-color02{
background-color:red;
}
.hid , .hid .box-size {
height:0px;
width:0px;
}
.uhid{
height:100px;
width:100px;
}
i add something to your code . Hope to sovle your issue.
you just need to find all elements in the desired class, iterate them and change their classes to the class that makes their color:
if (Show_This == 1)
{
document.getElementsByClassName("box-color02").forEach(function(element){
element.className = "box-size box-color01";});
}
if (Show_This == 2)
{
document.getElementsByClassName("box-color01").forEach(function(element){
element.className = "box-size box-color02";});
}

Synchronizing span and textarea scrollbars - scrollbar slightly off and pasting issue

I have a table set up in the following way, with each cell containing a span and a textarea:
<table>
<tr><td class="title">Original File</td></tr>
<tr><td><span id='ogline' onscroll="og.scrollTop=scrollTop"></span><span><textarea onscroll="ogline.scrollTop=scrollTop" onkeyup="linenumber()" id='og' onfocusout="linenumber()"></textarea></span></td></tr>
</table>
Along with that I have the following CSS:
<style>
span {
width:93%;
height: 100%;
}
textarea {
width:92%;
height: 100%;
border-style:solid;
border-color:black;
border-width:2px;
font-size:13px;
}
table {
width:100%;
height:100%;
}
.title {
height:5%;
text-align:center;
background-color:#009;
color:white;
}
#ogline {
padding-top:4px;
overflow:auto;
font-size:12px;
line-height:14.99px;
width:6%;
}
</style>
What I am trying to do is have the scroll bar of the span and the scroll bar of the textarea synch up. I've somewhat accomplished this using the onscroll event listener with the following code:
onscroll="og.scrollTop=scrollTop"
onscroll="ogline.scrollTop = scrollTop
This has somewhat accomplished what I want it to, with the span being about a line off of where it should be. The greatest problem I am having though is when I paste a large amount of text into the textarea. This almost completely doesn't work, with both scrollbars being completely off until I hold one of the scrollbars down for a significant amount of time before the other scrollbar will try to play catch up with the other.
Any suggestions? Is there maybe a better approach to this issue that I should try? Any help would be appreciated.
This could work:
var scrolling=false;
function og_scroll(el)
{
if (scrolling && el!=scrolling) {
return;
}
scrolling = el;
var textareas = document.getElementsByTagName('textarea');
for (var i=0; i<textareas.length; i++) {
if (textareas[i].id.indexOf('og')==0) { // searching for id==og*
textareas[i].scrollTop=el.scrollTop;
}
}
scrolling = false;
}
function up(num)
{
var area = document.getElementById('og'+num);
if (area.scrollTop > 0) {
area.scrollTop -= 15;
}
}
function down(num)
{
var area = document.getElementById('og'+num);
if (area.scrollTop < area.scrollHeight) {
area.scrollTop += 15;
}
}
function fix_mouse_scroll() {
var textareas = document.getElementsByTagName('textarea');
for (var i=0; i<textareas.length; i++) {
if (textareas[i].id.indexOf('og')==0) {
if ("onmousewheel" in document) {
textareas[i].onmousewheel = fixscroll;
} else {
textareas[i].addEventListener('DOMMouseScroll', fixscroll, false);
}
}
}
}
function fixscroll(event){
var delta=event.detail? event.detail : event.wheelDelta; // positive or negative number
delta = delta>0 ? 15 : -15;
event.target.scrollTop += delta;
//console.log(delta, ' with ',event.target.scrollTop);
}
Html part:
<tr><td> <span onmousedown='up(1)'>[UP]</span> <span onmousedown='down(1)'>[DOWN]</span> <textarea id='og1' onscroll="og_scroll(this);"></textarea></td></tr>
<tr><td> <span onmousedown='up(2)'>[UP]</span> <span onmousedown='down(2)'>[DOWN]</span> <textarea id='og2' onscroll="og_scroll(this);"></textarea></td></tr>
<tr><td> <span onmousedown='up(3)'>[UP]</span> <span onmousedown='down(3)'>[DOWN]</span> <textarea id='og3' onscroll="og_scroll(this);"></textarea></td></tr>
The full html code is here.

Elements "jerk" back to right when I change their order

I am trying to create an infinite scroll of elements, and haven't found a plugin that was sufficiently lightweight/capable enough, so I'm trying to create my own.
So far it is working swimmingly, except for a slight jerkiness in the animation when I remove the first element and append it to the end of the parent. The example I've tossed up also has an issue where the elements lose their padding, for some reason, but that is not occurring in my actual code...
Fiddle:
http://jsfiddle.net/WtFWy/
Using the sample markup:
<section id="photos" class="bg-transparent-black">
<div class="red"></div>
<div class="blue"></div>
<div class="green"></div>
</section>​
#photos{
position:absolute;
bottom:1em;
width:100px;
height:225px;
padding:3px;
overflow:hidden;
white-space:nowrap;
}
#photos div{
height:100%;
width:50px;
padding:3px;
display:inline-block;
position:relative;
border:1px solid black;
}
.red{background:red;}
.blue{background:blue;}
.green{background:green;}
​
And JavaScript:
scrollImages = function(){
var photoArea = $('#photos');
var children = photoArea.children();
var firstChild = $(children[0])
var firstOffset=firstChild.offset();
if(document.elementLeft === false){
document.elementLeft = firstOffset.left;
}
if(document.elementWidth === false){
document.elementWidth=firstChild.outerWidth(true);
}
if(firstOffset.left < 0 && (Math.abs(firstOffset.left) > Math.abs(document.elementWidth))){
photoArea.append(firstChild);
firstChild.css('margin-left', 0 + 'px')
children = photoArea.children();
firstChild = $(children[0])
firstOffset=firstChild.offset();
document.elementLeft = firstOffset.left;
document.elementWidth=firstChild.outerWidth(true);
}else{
}
document.elementLeft -= 1;
firstChild.css('margin-left', document.elementLeft + 'px');
t = setTimeout(scrollImages, 100);
}
document.elementLeft = false;
document.elementWidth = false;
var t = setTimeout(scrollImages, 500);
$('#photos').mouseover(function(){clearTimeout(t)});
$('#photos').mouseout(function(){scrollImages()})
});
​
If you remove the padding: 3px from #photos the animation works properly.

Categories