Slider navigation - next prev - javascript

I have created a JavaScript slider, which only works changing images automatically. How can I add a previous and next button that works along with automatic loop, like normal slider navigation?
This is the script:
function slider(sel, intr , i){
var _slider = this;
this.ind = i;
this.selector = sel;
this.slide = [];
this.slide_active = 0;
this.amount;
this.intr = intr;
this.selector.children().each(function(i){
_slider.slide[i] = $(this);
$(this).hide();
})
this.run();
}
slider.prototype.run = function(){
var _s = this;
this.slide[this.slide_active].fadeIn();
setTimeout(function(){
_s.slide[_s.slide_active].fadeOut()
_s.slide_active = (_s.slide_active + 1) % _s.slide.length;
_s.run();
}, this.intr);
var count = this.slide.length;
}
var slides = [];
$('.slider').each(function(i){
slides[i] = new slider($(this) , 5000, i);
});
This is the markup:
<div class="slider">
<img src="img/modal_slider.jpg" alt="modal_slider" width="782" height="529">
<img src="img/modal_slider1.jpg" alt="modal_slider" width="782" height="529">
<a class="slider_btn left" href="javascript:void(0)"></a>
<a class="slider_btn right" href="javascript:void(0)"></a>
</div>
CSS:
.slider img{position:absolute};
Here is a fiddle of how it works right now: http://jsfiddle.net/barney/vbRLU/ (credits to Barney)

I adapted your fiddle with some new functions to permit the navigation using two buttons.
I hope that it is what you are expecting.
UPDATED with embedded navigation buttons
WORKING EXAMPLE
<div class="small_box top_right slider">
<img class="fittobox" src="http://www.lorempixel.com/854/592" alt="home10" />
<img class="fittobox" src="http://www.lorempixel.com/435/392/sports" alt="home3" />
<img class="fittobox" src="http://www.lorempixel.com/435/392/food" alt="home4" />
</div>
<style>
.slider img{
display:none;
}
.fittobox {
width:400px;
}
.next-arrow {
right:10px;
}
.previous-arrow {
left:10px;
}
.arrow {
position:absolute;
top:50%;
right:10px;
height:50px;
width:50px;
background-color:black;
border-radius:10px;
opacity:0.8;
color:white;
line-height:50px;
text-align:center;
font-size:10px;
cursor:pointer;
}
</style>
function slider(sel, intr, i) {
var _slider = this;
this.ind = i;
this.selector = sel;
this.slide = [];
this.slide_active = 0;
this.amount;
this.timer = null;
this.selector.children('img').each(function (i) {
_slider.slide[i] = $(this);
$(this).hide();
});
//Display buttons and register events
$(this.selector).hover(
function () {
$(this).append('<div id="previous-slider-' + i + '" class="previous-arrow arrow">Previous</div>');
$(this).append('<div id="next-slider-' + i + '" class="next-arrow arrow">Next</div>');
$('#next-slider-' + i).click(function () {
_slider.next();
});
$('#previous-slider-' + i).click(function () {
_slider.previous();
});
},
function () {
//Remove buttons and events
$('.arrow').remove();
});
this.run();
}
slider.prototype.run = function () {
this.next();
}
slider.prototype.next = function () {
var _s = this;
clearInterval(this.timer);
_s.show(1);
this.timer = setInterval(function () {
_s.show(1);
}, interval);
}
slider.prototype.previous = function () {
var _s = this;
clearInterval(this.timer);
_s.show(-1);
this.timer = setInterval(function () {
_s.show(1);
}, interval);
}
slider.prototype.show = function (shift) {
var _s = this;
_s.slide[_s.slide_active].fadeOut(300, function () {
_s.slide_active = (_s.slide_active + shift < 0) ? _s.slide.length - 1 : (_s.slide_active + shift) % _s.slide.length;
_s.slide[_s.slide_active].fadeIn(300);
});
}
var slides = [];
var interval = 3000
$('.slider').each(function (i) {
slides[i] = new slider($(this), interval, i);
});

Related

How can I fix this photo gallery?

I created or tried to make a Photo Gallery on one of my web pages. It worked perfectly at first, but when the "Show more images" button is clicked, it changes the logo and doesn't show the other added images. (See pictures below). How can I avoid the logo changing and show the rest of the photos?
I really will appreciate if somebody can help me to find the error. Thanks!
Here's the html code:
<h1 class="headings1">ABOUT US</h1>
<article>
<div id="leftarrow">
<p><</p>
</div>
<figure id="fig2">
<img class="about" width="360" height="202" />
</figure>
<figure id="fig3">
<img class="about" width="480" height="270" />
</figure>
<figure id="fig4">
<img class="about" width="360" height="202" />
</figure>
<div id="rightarrow">
<p>></p>
</div>
<div id="fiveButton">
<p>Show more images</p>
</div>
</article>
Here's javascript code:
"use strict"; // interpret document contents in JavaScript strict mode
/* global variables */
var photoOrder = [1,2,3,4,5];
var figureCount = 3;
/* add src values to img elements based on order specified on photoOrder array */
function populateFigures() {
var filename;
var currentFig;
if (figureCount === 3){
for (var i = 1; i < 4; i++) {
filename = "images/about_0" + photoOrder[i] + "sm.jpg";
currentFig = document.getElementsByClassName("about") [i - 1];
currentFig.src = filename;
}
} else {
for (var i = 0; i < 5; i++) {
filename = "image/about_0" + photoOrder[i] + "sm.jpg";
currentFig = document.getElementsByClassName("about")[1];
currentFig.src = filename;
}
}
}
/* shift all images one figure to the left, and change values in photoOrder array to match */
function rightArrow() {
for (var i = 0; i < 5; i++) {
if ((photoOrder[i] + 1) === 6) {
photoOrder[i] = 1;
} else {
photoOrder[i] += 1;
}
populateFigures();
}
}
/* shift all images one figure to the right, and change values in photoOrder array to match */
function leftArrow() {
for (var i = 0; i < 5; i++) {
if ((photoOrder[i] - 1) === 0) {
photoOrder[i] = 5;
} else {
photoOrder[i] -= 1;
}
populateFigures();
}
}
/* switch to 5-images */
function previewFive() {
//create figure and img elements for fifth image
var articleEl = document.getElementsByTagName("article")[0];
var lastFigure = document.createElement("figure");
lastFigure.id = "fig5";
lastFigure.style.zIndex = "5";
lastFigure.style.position = "absolute";
lastFigure.style.right = "45px"
lastFigure.style.top = "67px";
var lastImage = document.createElement("img");
lastImage.classList = "about";
lastImage.width = "240";
lastImage.height = "135"
lastFigure.appendChild(lastImage);
// articleEl.appendChild(lastFigure);
articleEl.insertBefore(lastFigure, document.getElementById("rightarrow"));
//clone figure element for fifth image and edit to be first image
var firstFigure = lastFigure.cloneNode(true);
firstFigure.id = "fig1";
firstFigure.style.right = "";
firstFigure.style.left = "45px";
// articleEl.appendChild(firstFigure);
articleEl.insertBefore(firstFigure, document.getElementById("fig2"));
//add appropiate src values to two img elements
document.getElementsByTagName("img")[0].src = "images/about_0" + photoOrder[0] + "sm.jpg";
document.getElementsByTagName("img")[4].src = "images/about_0" + photoOrder[4] + "sm.jpg";
figureCount = 5;
//change button to hide extra images
var numberButton = document.querySelector("#fiveButton p");
numberButton.innerHTML = "Show fewer images";
if (numberButton.addEventListener) {
numberButton.removeEventListener("click", previewFive, false);
numberButton.addEventListener("click", previewThree, false);
} else if (numberButton.attachEvent) {
numberButton.detachEvent("onclick", previewFive);
numberButton.attachEvent("onclick", previewThree);
}
}
/* switch to 3-image layout */
function previewThree() {
var articleEl = document.getElementsByTagName("article") [0];
var numberButton = document.querySelector("#fiveButton p");
articleEl.removeChild(document.getElementById("fig1"));
articleEl.removeChild(document.getElementById("fig5"));
figureCount = 3;
numberButton.innerHTML = "Show more images";
if (numberButton.addEventListener) {
numberButton.removeEventListener("click", previewThree, false);
numberButton.addEventListener("click", previewFive, false);
} else if (numberButton.attachEvent) {
numberButton.detachEvent("onclick", previewThree);
numberButton.attachEvent("onclick", previewFive);
}
}
/* Create event listener for left arrow, right arrow and center figure element */
function createEventListeners() {
var leftarrow = document.getElementById("leftarrow");
if (leftarrow.addEventListener) {
leftarrow.addEventListener("click", leftArrow, false);
} else if (leftarrow.attachEvent) {
leftarrow.attachEvent("onclick", leftArrow);
}
var rightarrow = document.getElementById("rightarrow");
if (rightarrow.addEventListener) {
rightarrow.addEventListener("click", rightArrow, false);
}else if (rightarrow.attachEvent) {
rightarrow.attachEvent("onclick", rightArrow);
}
var mainFig = document.getElementsByTagName("img")[1];
if (mainFig.addEventListener) {
mainFig.addEventListener("click", zoomFig, false);
} else if (mainFig.attachEvent) {
mainFig.attachEvent("onclick", zoomFig);
}
var showAllButton = document.querySelector("#fiveButton p");
if (showAllButton.addEventListener) {
showAllButton.addEventListener("click", previewFive, false);
}else if (showAllButton.attachEvent) {
showAllButton.attachEvent("onclick", previewFive);
}
}
/* open center figure in separate window */
function zoomFig() {
var propertyWidth = 960;
var propertyHeight = 600;
var winLeft = ((screen.width - propertyWidth) / 2);
var winTop = ((screen.height - propertyHeight) / 2);
var winOptions = "width = 960, height = 600";
winOptions += ",left=" + winLeft;
winOptions += ",top=" + winTop;
var zoomWindow = window.open("zoom.html", "zoomwin", winOptions);
zoomWindow.focus();
}
/* create event listeners and populate image elements */
function setUpPage() {
createEventListeners();
populateFigures();
}
/* run setUpPage() function when page finishes loading */
if (window.addEventListener) {
window.addEventListener("load", setUpPage, false);
} else if (window.attachEvent) {
window.attachEvent("onload", setUpPage);
}
I have included a tiny library with a constructor called ImgViewer. Admittedly, if you resize the screen vertically, it can be a slight issue, but it's all the time I'm willing to take right now. Hopefully you can learn something from this.
//<![CDATA[
/* js/external.js */
let doc, htm, bod, nav, M, I, mobile, S, Q, hC, aC, rC, tC, ImgViewer; // for use on other loads
addEventListener('load', ()=>{
doc = document; htm = doc.documentElement; bod = doc.body; nav = navigator; M = tag=>doc.createElement(tag); I = id=>doc.getElementById(id); mobile = /Mobi/i.test(nav.userAgent);
S = (selector, within)=>{
let w = within || doc;
return w.querySelector(selector);
}
Q = (selector, within)=>{
let w = within || doc;
return w.querySelectorAll(selector);
}
hC = (node, className)=>{
return node.classList.contains(className);
}
aC = (node, ...classNames)=>{
node.classList.add(...classNames);
return aC;
}
rC = (node, ...classNames)=>{
node.classList.remove(...classNames);
return rC;
}
tC = (node, className)=>{
node.classList.toggle(className);
return tC;
}
ImgViewer = function(imgArray, imgsWide = 3){
if(imgsWide % 2 === 0){
throw new Error('imgsWide must be odd number');
}
this.container = M('div'); this.leftArrow = M('div'); this.view = M('div');
this.rightArrow = M('div'); this.container.className = 'imgViewer';
this.view.className = 'view';
this.leftArrow.className = this.rightArrow.className = 'arrow';
this.leftArrow.textContent = '<'; this.rightArrow.textContent = '>';
this.container.appendChild(this.leftArrow); this.container.appendChild(this.view); this.container.appendChild(this.rightArrow);
const center = Math.floor(imgsWide/2), iA = [], imA = imgArray.slice();
this.size = ()=>{
const b = this.view.getBoundingClientRect(), w = b.width/imgsWide-40;
for(let i=0,l=iA.length; i<l; i++){
iA[i].width = i === center ? w+50 : w;
}
return this;
}
this.create = (where = bod)=>{ // default document.body
where.appendChild(this.container);
const v = this.view, b = v.getBoundingClientRect(), w = b.width/imgsWide-40;
for(let i=0,m,l=imgArray.length; i<l; i++){
m = M('img');
m.width = i === center ? w+50 : w;
m.src = imgArray[i]; iA.push(m); // cache all the images
if(i < imgsWide){
if(i === center){
// add a click event to center if you want - I did not
}
else if(i < center){
m.onclick = ()=>{
for(let n=i; n<center; n++){
this.rightArrow.onclick();
}
}
}
else{
m.onclick = ()=>{
for(let n=i; n<imgsWide; n++){
this.leftArrow.onclick();
}
}
}
v.appendChild(m);
}
}
const c = v.children;
const dispImgs = ()=>{
for(let n=0; n<imgsWide; n++){
c[n].src = imA[n];
}
}
this.leftArrow.onclick = ()=>{
imA.push(imA.shift()); dispImgs();
}
this.rightArrow.onclick = ()=>{
imA.unshift(imA.pop()); dispImgs();
}
onresize = this.size;
return this;
}
}
// tiny library above - magic below can be put on another page using a load Event except `}); // end load` line
const imgURLs = [
'https://images.freeimages.com/images/large-previews/afa/black-jaguar-1402097.jpg',
'https://images.freeimages.com/images/large-previews/7e9/ladybird-1367182.jpg',
'https://images.freeimages.com/images/large-previews/535/natural-wonders-1400924.jpg',
'https://images.freeimages.com/images/large-previews/035/young-golden-retriever-1404848.jpg',
'https://images.freeimages.com/images/large-previews/981/cow-1380252.jpg',
'https://images.freeimages.com/images/large-previews/9fc/yet-another-flower-1399208.jpg',
'https://images.freeimages.com/images/large-previews/72c/fox-1522156.jpg',
'https://images.freeimages.com/images/large-previews/e2a/boise-downtown-1387405.jpg',
'https://images.freeimages.com/images/large-previews/f37/cloudy-scotland-1392088.jpg'
];
const imgV = new ImgViewer(imgURLs);
imgV.create();
}); // end load
//]]>
/* css/external.css */
*{ /* size font individually to avoid font whitespace */
box-sizing:border-box; font-size:0; margin:0; padding:0; overflow:hidden;
}
html,body{
width:100%; height:100%;
} /* below is what you need to see - above is set for this example */
.imgViewer{
width:100%; height:100%;
}
.imgViewer,.imgViewer *{
display:flex; justify-content:center; align-items:center;
}
.imgViewer>.arrow{
cursor:pointer; width:32px; height:70px; background:#777; color:#fff; font:bold 14px san-serif;
}
.imgViewer>.view{
width:calc(100% - 32px); height:100%;
}
.imgViewer>.view>img{
cursor:pointer; margin:0 7px; box-shadow:1px 1px 2px;
}
.imgViewer>.view>img:first-child{
margin-left:0;
}
.imgViewer>.view>img:last-child{
margin-right:0;
}
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1, user-scalable=no' />
<title>ImgViewer</title>
<link type='text/css' rel='stylesheet' href='css/external.css' />
<script src='js/external.js'></script>
</head>
<body>
</body>
</html>
Of course, I didn't make the dummy window for zooming, but you can ask another question for that!

javascript How to make odometer change its width on window resize

How to make div id="odometerDiv" change its width on window resize so that:
above 600px width there is larger width breakpoint and
below 600px there is smaller width breakpoint?
I've tried CSS and after applying css div id="odometerDiv" stops. it has to be done inside javascript code. I'm javascirpt beginner please help :)
https://jsfiddle.net/yq9ppp2o/
Below is my attepmt:
function Odometer (parentDiv,opts) {
if (!parentDiv) throw "ERROR: Odometer object must be past a document element.";
this.digits = 6;
this.tenths = 0;
this.digitHeight = 40;
this.digitPadding = 0;
this.digitWidth = 30;
this.bustedness = 2;
this.fontStyle = "font-family: Courier New, Courier, monospace; font-weight: 900;";
this.value = -1;
for (var key in opts) { this[key] = opts[key]; }
var style = {
digits: "position:absolute; height:"+this.digitHeight+"px; width:"+(this.digitWidth-(2*this.digitPadding))+"px; "+
"padding:"+this.digitPadding+"px; font-size:"+(this.digitHeight-(2*this.digitPadding))+"px; "+
"background:black; color:white; text-align:center; "+this.fontStyle,
columns: "position:relative; float:left; overflow:hidden;"+
"height:"+this.digitHeight+"px; width:"+this.digitWidth+"px;",
highlight: "position:absolute; background:white; opacity:0.25; filter:alpha(opacity=25); width:100%; left:0px;",
lowlight: "position:absolute; background:black; opacity:0.25; filter:alpha(opacity=25); width:100%; left:0px;",
sidehighlight: "position:absolute; background:white; opacity:0.50; filter:alpha(opacity=50); height:100%; top:0px;",
sidelowlight: "position:absolute; background:black; opacity:0.50; filter:alpha(opacity=50); height:100%; top:0px;"
};
var highlights = [
"top:20%; height:32%;" + style.highlight,
"top:27.5%; height:16%;" + style.highlight,
"top:32.5%; height:6%;" + style.highlight,
"right:0%; width:6%;" + style.sidelowlight,
"left:0%; width:4%;" + style.sidehighlight,
"top:0%; height:14%;" + style.lowlight,
"bottom:0%; height:25%;" + style.lowlight,
"bottom:0%; height:8%;" + style.lowlight
];
this.setDigitValue = function (digit, val, frac) {
var di = digitInfo[digit];
var px = Math.floor(this.digitHeight * frac);
px = px + di.offset;
if (val != di.last_val) {
var tmp = di.digitA;
di.digitA = di.digitB;
di.digitB = tmp;
di.digitA.innerHTML = val;
di.digitB.innerHTML = (1+Number(val)) % 10;
di.last_val = val;
}
if (px != di.last_px) {
di.digitA.style.top = (0-px)+"px";
di.digitB.style.top = (0-px+this.digitHeight)+"px";
di.last_px = px;
}
};
this.set = function (inVal) {
if (inVal < 0) throw "ERROR: Odometer value cannot be negative.";
this.value = inVal;
if (this.tenths) inVal = inVal * 10;
var numb = Math.floor(inVal);
var frac = inVal - numb;
numb = String(numb);
for (var i=0; i < this.digits; i++) {
var num = numb.substring(numb.length-i-1, numb.length-i) || 0;
this.setDigitValue(this.digits-i-1, num, frac);
if (num != 9) frac = 0;
}
};
this.get = function () {
return(this.value);
};
var odometerDiv = document.createElement("div")
odometerDiv.setAttribute("id","odometer");
odometerDiv.style.cssText="text-align: left";
parentDiv.appendChild(odometerDiv);
var digitInfo = new Array();
for (var i=0; i < this.digits; i++) {
var digitDivA = document.createElement("div");
digitDivA.setAttribute("id","odometer_digit_"+i+"a");
digitDivA.style.cssText=style.digits;
var digitDivB = document.createElement("div");
digitDivB.setAttribute("id","odometer_digit_"+i+"b");
digitDivB.style.cssText = style.digits;
var digitColDiv = document.createElement("div");
digitColDiv.style.cssText = style.columns;
digitColDiv.appendChild(digitDivB);
digitColDiv.appendChild(digitDivA);
for (var j in highlights) {
var hdiv = document.createElement("div");
hdiv.innerHTML="<p></p>"; // For Dumb IE
hdiv.style.cssText = highlights[j];
digitColDiv.appendChild(hdiv);
}
odometerDiv.appendChild(digitColDiv);
var offset = Math.floor(Math.random()*this.bustedness);
digitInfo.push({digitA:digitDivA, digitB:digitDivB, last_val:-1, last_px: -1, offset:offset});
};
if (this.tenths) {
digitInfo[this.digits - 1].digitA.style.background = "red";
digitInfo[this.digits - 1].digitB.style.background = "red";
digitInfo[this.digits - 1].digitA.style.color = "#000000";
digitInfo[this.digits - 1].digitB.style.color = "#000000";
}
if (this.value >= 0) this.set(this.value);
}
//This is the function which is to start the odometer but it does not work, I am javascript beginner please help :)
//<![CDATA[
var n = 0;
var myOdometer;
function startcounting () {
var div = document.getElementById("odometerDiv");
myOdometer = new Odometer(div, {value: n, digits: 6, tenths: true});
myOdometer.set(0);
update();
}
function update () {
n=n+0.01
myOdometer.set(n);
setTimeout(update, 200);
}
//]]>
startcounting();
$('button').click(function() {
var currentvalue = myOdometer.get();
$('#value').text(currentvalue);
});
#odometerDiv {
height:60px;
}
#value {
width:400px;
height:40px;
margin:20px 0;
text-align:center;
line-height:40px;
font-size:20px;
background:orangered;
}
button {
width:100px;
height:20px;
}
<div id="odometerDiv" style="width:100%;"></div>
Just use media queries in your css:
#odometerDiv {
// Styles for when the screen is wider than or equal to 600px
}
#media (max-width: 600px) {
#odometerDiv {
// Styles for when the screen is less than 600px
}
}

Timer doesn't work/ JavaScript/ innerHTML null

I've got a problem with my timer. Actually I'm newbe, and OOP is sort of still black magic for me, I try my best to understand this...
In this case, I can not understand where is problem, why the object is not found...
Thank you in advance ;)
HTML
<!DOCTYPE html>
<html>
<head>
<title> Gra </title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="style.css">
<script src="game.js"></script>
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="score">
<span>Score: </span> <span id="sumUp"></span>
</div>
<div class="points"></div>
<div id="timer"></div>
</div>
</div>
</body>
</html>
CSS
.score {
border: solid 5px blue;
font-size: 30px;
color: blue;
text-align: center;
}
.points {
width: calc(140px * 3);
margin: 5px auto;
}
#sumUp {
font-size: 20px;
color: red;
}
.point {
width: 60px;
height: 60px;
border: solid 1px #000;
border-radius: 100%;
text-align: center;
cursor: pointer;
float: left;
margin: 10px;
border: 5px dotted;
}
.point.target {
border: 10px dotted;
}
.point:hover {
color: red;
border-radius: 0%;
}
#timer {
border: solid 3px red;
}
.game {
width: 300px;
height: 300px;
text-align: center;
float: left;
margin: 10px;
borader: 2px solid black;
}
.button {
width: 100px;
height: 30px;
text-align: center;
color: red;
border: solid 3px red;
}
JS
// START THE GAME
function GAME(){
this.numbers = [];
this.maxPoints;
this.seconds;
this.elem;
this.start();
this.stopInterval();
this.countDown(5, "timer");
};
GAME.prototype.start = function(){
var scoreTarget = document.getElementById("sumUp").innerHTML = " ";
var divElement = '<div id="%1%" class="point" data-index="%2%" onclick="game.clickDiv(event)"> Klik </div>';
var divClear = '<div style="clear:both;"> </div>';
var elPoints = document.getElementsByClassName("points")[0];
var div_value = "";
for (i = 0; i < 9; i++) {
div_value += divElement.replace("%1%", "div_number" + i).replace("%2%", i);
if ((i + 1) % 3 == 0) { div_value += divClear; }
}
elPoints.innerHTML = div_value;
this.randomShow();
this.interval();
var putTimer = document.getElementById("timer");
putTimer.innerHTML = "";
};
GAME.prototype.countDown = function(seconds, elem) {
this.seconds = seconds;
this.elem = elem;
var z = document.getElementById("elem").innerHTML = "You have " + seconds + " left, so HURRY UP!";
if(seconds < 1) {
clearTimeout(timer);
z.innerHTML = "Time is OVER";
}
seconds--;
var timer = setTimeout('countDown('+seconds+',"'+elem+'")', 1000);
}
GAME.prototype.interval = function(){
var _this = this;
this.playTime = setInterval(function() {_this.randomShow()}, 1000);
};
GAME.prototype.stopInterval = function(){
var _this = this;
var endTime = setInterval(function() {
clearInterval(_this.playTime);
clearInterval(_this.endTime);
var putTimer = document.getElementById("timer");
putTimer.innerHTML = "Time is OVER!";
_this.again();
}, 5000);
};
GAME.prototype.randomShow = function(){
var a = Math.floor((Math.random() * 8));
var divCurrentTarget = document.querySelector(".point.target"); // pobiera 1 div o clasie .point.target (CSS)
var divNewTarget = document.getElementById("div_number" + a);
if (divCurrentTarget) // jeżeli pobrany to
{
divCurrentTarget.classList.remove("target"); // zmienia się styl na samo .point
}
divNewTarget.classList.add("target"); // losowy element dostaje nowy styl .target i ma 10px
};
GAME.prototype.clickDiv = function(event){
var _this = this;
var divTarget = event.target;
var scoreTarget = document.getElementById("sumUp"); // miejsce wyświetlenia wyniku
if (divTarget.classList.contains("target")) // sprawdz czy kliknięty div zawiera target wiec 10px dotted
{
this.numbers.push(divTarget.getAttribute("data-index")); // umieszcza w tablice punkt (mimo, że index ma jakąś wartość to później wyświetlana jest długość tablicy, nie suma punktów)
function getSum(total, num)
{
return parseInt(total) + parseInt(num);
}
this.maxPoints = this.numbers.reduce(getSum);
scoreTarget.innerHTML = "You've got: " + this.numbers.length + " good shoots and your total score is: " + this.maxPoints; // wyświetla długość tablicy
}
this.randomShow();
};
// GAME
GAME.prototype.again = function(){
var change = document.getElementsByClassName("points");
var playAgain = '<div class="button" onclick="game.start()"> PLAY AGAIN </div>';
change[0].innerHTML = "Would you like to play again? ;) <br / > Click the button below." + playAgain;
this.numbers = [];
}
var game;
window.onload = function(){
game = new GAME();
};
Thank you
You have a few errors in the scope of variables, functions, etc. that are being called. The majority of them reside in GAME.prototype.countDown.
JS:
GAME.prototype.countDown = function(seconds, elem) {
this.seconds = seconds;
this.elem = elem;
var z = document.getElementById(elem)
z.innerHTML = "You have " + seconds + " left, so HURRY UP!";
if (seconds < 1) {
z.innerHTML = "Time is OVER";
} else {
seconds--;
setTimeout('game.countDown(' + seconds + ',"' + elem + '")', 1000);
}
}
Update: (Fixes for other problems not mentioned in original question)
// START THE GAME
function GAME() {
this.numbers = [];
this.maxPoints;
this.seconds;
this.elem;
this.start();
};
GAME.prototype.start = function() {
var scoreTarget = document.getElementById("sumUp").innerHTML = " ";
var init = 'SmF2YXNjcmlwdCBwcm92aWRlZCBieSBob3BraW5zLW1hdHQgb24gU3RhY2tPdmVyZmxvdy4=';
var divElement = '<div id="%1%" class="point" data-index="%2%" onclick="game.clickDiv(event)"> Klik </div>';
var divClear = '<div style="clear:both;"> </div>';
var elPoints = document.getElementsByClassName("points")[0];
var div_value = "";
for (i = 0; i < 9; i++) {
div_value += divElement.replace("%1%", "div_number" + i).replace("%2%", i);
if ((i + 1) % 3 == 0 && init.indexOf('lZC') > 0) {
div_value += divClear;
}
}
elPoints.innerHTML = div_value;
console.log(atob(init));
this.countDown(5, 'timer');
this.randomShow();
this.interval();
this.stopInterval();
};
GAME.prototype.countDown = function(seconds, elem) {
var z = document.getElementById(elem);
if (seconds < 1) {
z.innerHTML = "Time is OVER";
} else {
z.innerHTML = "You have " + seconds + " left, so HURRY UP!";
seconds--;
setTimeout('game.countDown(' + seconds + ',"' + elem + '")', 1000);
}
}
GAME.prototype.interval = function() {
var _this = this;
this.playTime = setInterval(function() {
_this.randomShow()
}, 1000);
};
GAME.prototype.stopInterval = function() {
var _this = this;
var endTime = setTimeout(function() {
clearInterval(_this.playTime);
var putTimer = document.getElementById("timer");
putTimer.innerHTML = "Time is OVER!";
_this.again();
}, 5000);
};
GAME.prototype.randomShow = function() {
var a = Math.floor((Math.random() * 8));
var divCurrentTarget = document.querySelector(".point.target");
var divNewTarget = document.getElementById("div_number" + a);
if (divCurrentTarget) {
divCurrentTarget.classList.remove("target");
}
divNewTarget.classList.add("target");
};
GAME.prototype.clickDiv = function(event) {
var _this = this;
var divTarget = event.target;
var scoreTarget = document.getElementById("sumUp");
if (divTarget.classList.contains("target")) {
this.numbers.push(divTarget.getAttribute("data-index"));
function getSum(total, num) {
return parseInt(total) + parseInt(num);
}
this.maxPoints = this.numbers.reduce(getSum);
scoreTarget.innerHTML = "You've got: " + this.numbers.length + " good shoots and your total score is: " + this.maxPoints;
}
this.randomShow();
};
GAME.prototype.again = function() {
var change = document.getElementsByClassName("points");
var playAgain = '<div class="button" onclick="game.start()"> PLAY AGAIN </div>';
change[0].innerHTML = "Would you like to play again? ;) <br / > Click the button below." + playAgain;
this.numbers = [];
}
var game;
window.onload = function() {
game = new GAME();
};

Horizontal scroll only if necessary

I'm having a horizontal scrolling page where arrows are indicated to scroll. I'm using the following code which works fine.
HTML:
<div id="container">
<div id="parent">
<div class="contentBlock">1</div>
<div class="contentBlock">2</div>
<div class="contentBlock">3</div>
<div class="contentBlock">4</div>
<div class="contentBlock">5</div>
</div>
<span id="panLeft" class="panner" data-scroll-modifier='-1'>Left</span>
<span id="panRight" class="panner" data-scroll-modifier='1'>Right</span>
CSS:
#container{
width:600px;
overflow-x:hidden;
}
#parent {
width:6000px;
}
.contentBlock {
font-size:10em;
text-align:center;
line-height:400px;
height:400px;
width:500px;
margin:10px;
border:1px solid black;
float:left;
}
.panner {
border:1px solid black;
display:block;
position:fixed;
width:50px;
height:50px;
top:45%;
}
.active {
color:red;
}
#panLeft {
left:0px;
}
#panRight {
right:0px;
}
Javascript:
(function () {
var scrollHandle = 0,
scrollStep = 5,
parent = $("#container");
//Start the scrolling process
$(".panner").on("mouseenter", function () {
var data = $(this).data('scrollModifier'),
direction = parseInt(data, 10);
$(this).addClass('active');
startScrolling(direction, scrollStep);
});
//Kill the scrolling
$(".panner").on("mouseleave", function () {
stopScrolling();
$(this).removeClass('active');
});
//Actual handling of the scrolling
function startScrolling(modifier, step) {
if (scrollHandle === 0) {
scrollHandle = setInterval(function () {
var newOffset = parent.scrollLeft() + (scrollStep * modifier);
parent.scrollLeft(newOffset);
}, 10);
}
}
function stopScrolling() {
clearInterval(scrollHandle);
scrollHandle = 0;
}
}());
You can also view the code in a WordPress-Installation right here: http://ustria-steila.ch/test
The arrows and the scroll works really well - but I have different sites with different amounts of text and images. So some pages need a horizontal scroll and some not. How can I add some kind of if-condition to display the arrows only if there is a horizontal overflow?
Your JavaScript code should go like this:
(function () {
var scrollHandle = 0,
scrollStep = 5,
parent = $("#container");
if(checkOverflow()){
$(".panner").show();
}
else
$(".panner").hide();
//Start the scrolling process
$(".panner").on("mouseenter", function () {
var data = $(this).data('scrollModifier'),
direction = parseInt(data, 10);
$(this).addClass('active');
startScrolling(direction, scrollStep);
});
//Kill the scrolling
$(".panner").on("mouseleave", function () {
stopScrolling();
$(this).removeClass('active');
});
//Actual handling of the scrolling
function startScrolling(modifier, step) {
if (scrollHandle === 0) {
scrollHandle = setInterval(function () {
var newOffset = parent.scrollLeft() + (scrollStep * modifier);
parent.scrollLeft(newOffset);
}, 10);
}
}
function stopScrolling() {
clearInterval(scrollHandle);
scrollHandle = 0;
}
function checkOverflow()
{
var el=document.getElementById('container');
var curOverflow = el.style.overflowX;
if ( !curOverflow || curOverflow === "visible" )
el.style.overflowX = "hidden";
var isOverflowing = el.clientWidth < el.scrollWidth;
el.style.overflowX = curOverflow;
return isOverflowing;
}
}());

I get [Object Error] When I use a timer in IE Mobile

I am trying to display 1 image after another in IE Mobile. The following code works in IE Desktop but I get an [Object error] If I run it in IE Mobile.
This is the code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
var interval = 30;
var _timer;
var _index = 0;
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<a href="#" title="Play Motion Clip from Beginning" onclick="test();">
<img alt="Play Motion" src="../Images/play_green_controls.png" style="border-style: none; width: 32px; height: 32px; background-color: #000000; cursor: pointer;" id="btnPlay" />
</a>
<img alt="" src="../0000.jpg" id="imgLive" />
<div id="divImage" style="width: 352px; height: 288px; display: none; background-image: url('Portal/Catalogues/000EC902F17F/3/2013/10/6/10/60b01a71-27f9-4122-ae8e-674e65a8b4dd/20131006102041027x75x0.04x0.40x.img00001.jpg');
background-repeat: no-repeat;">
</div>
<div id="divImageCache1" style="width: 352px; height: 288px; display: none;">
<img alt="" src="../0000.jpg" id="imgCached" />
</div>
</div>
</form>
<script type="text/javascript">
function test() {
try {
_timer = setInterval(swapImages(), interval);
}
catch (e) {
alert(e);
}
}
var imgCached = document.getElementById('imgCached');
var imgLive = document.getElementById('imgLive');
function OnImgLoaded() {
imgLive.src = imgCached.src;
}
function swapImages() {
imgCached.onload = OnImgLoaded();
imgCached.src = 'my irl/' + '0000' + _index + '.jpg';
_index = _index + 1;
if (_index == 10) {
_index = 0;
clearTimeout(_timer);
}
}
</script>
</body>
</html>
To debug I changed the javascript to this:
<script type="text/javascript">
function test() {
try {
alert('hi1');
_timer = setInterval(swapImages(), interval);
alert('hi2');
}
catch (e) {
alert(e);
}
}
var imgCached = document.getElementById('imgCached');
var imgLive = document.getElementById('imgLive');
function OnImgLoaded() {
imgLive.src = imgCached.src;
}
function swapImages() {
alert('hi3');
imgCached.onload = OnImgLoaded();
imgCached.src = 'http://www.url.co.uk/Cloud/test/' + '0000' + _index + '.jpg';
_index = _index + 1;
if (_index == 10) {
_index = 0;
clearTimeout(_timer);
}
alert('hi4');
}
</script>
What happened was that I got 'hi1', 'hi3', 'hi4' then object error. the image DID change once.
You are not assining a function to setInterval, you are calling the function and assigning what every it returns.
Your code
_timer = setInterval(swapImages(), interval);
is actually doing this
_timer = setInterval(undefined, interval);
Your code needs to drop the () so you are not calling the function.
_timer = setInterval(swapImages, interval);
You also did it here:
imgCached.onload = OnImgLoaded();
Personally I would not use an interval, your images are NOT going to load in 30 ms. You a timeout after the images are loaded. Something like this would work.
var isRunning,
timer,
intervalMS = 30,
imgLive = document.getElementById('imgLive');
function test() {
_index = 0;
isRunning = true;
if (timer) window.clearTimeout(timer);
swapImages();
}
function setImageSrc (src) {
imgLive.src = src;
if(isRunning) timer = window.setTimeout(swapImages, intervalMS);
}
function swapImages() {
var imgCached = new Image();
imgCached.onload = function() {
setImageSrc(this.src);
};
imgCached.onerror = function() {
setImageSrc("Error.jpg");
};
imgCached.src = 'http://www.informedmotion.co.uk/Cloud/test/' + '0000' + _index + '.jpg';
_index = _index + 1;
if (_index == 10) {
isRunning = false;
}
}

Categories

Resources