Unable to update CSS coloring using JavaScript - javascript

I've been trying to make this work for a while and for some reason the colors aren't updating. If I had to guess, it has to do with my returning an invalid string, but I'm not sure. The intended result is it converts the hours, minutes, and seconds into hexadecimal values respectively, but for some reason it is not working. If anyone can help it would be greatly appreciated. Thanks!
var div = document.getElementById("full");
function getclockColor() {
var h = toString(today.getHours());
var m = toString(today.getMinutes());
var s = toString(today.getSeconds());
color = '#' + h + m + s;
}
return color;
}
function changeColor() {
div.style.backgroundColor = getclockColor();
}
setInterval(changeColor, 1000);
body {
overflow: hidden;
margin: 0;
padding: 0;
}
#full {
position: absolute;
height: 100%;
width: 100%;
}
<link rel="stylesheet" type="text/css" href="/Users/zanolon/Desktop/Color Clock/Clock.css">
<div id="full"></div>

You have multiple errors:
You are invoking return outside your getclockColor function (and you have an extra }).
There is no today object. From your code I assume you want a Date object newly generated (with the current date). You can create a Date object like this: new Date().
This is not an error, but just so you know, you don't need to convert the numbers to string. It will automatically cast the values to string when concatenating to a string with the + operator.
Consider adding a zero when the number only contains one digit, because otherwise you will find many cases where the string generated will have less than 6 digits (plus the #).
The idea doesn't make that much sense, because you are combining three "random" numbers into a string. In many cases this won't result in a valid hex color string. You could try using the hsl format instead, which looks like this: hsl(120, 100%, 50%). You can achieve this easily with string templates: ` hsl(${h}, ${m}%, ${s}%) `
var div = document.getElementById("full");
function getclockColor() {
const today = new Date()
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
color = '#' + h + m + s;
return color;
}
function changeColor() {
div.style.backgroundColor = getclockColor();
}
setInterval(changeColor, 1000);
body {
overflow: hidden;
margin: 0;
padding: 0;
}
#full {
position: absolute;
height: 100%;
width: 100%;
}
<link rel="stylesheet" type="text/css" href="/Users/zanolon/Desktop/Color Clock/Clock.css">
<div id="full"></div>

Several issues:
You have an extra dangling } there (Which is why you're getting the illegal return statement). You cannot return when not in a function.
Also, today is not set anywhere.
There is no function called toString(). toString() is a method on number, so you can call it like so: today.getHours().toString()
You might want to consider 0 padding your h, m, and s if they're < 10, as you may be getting invalid hex codes (4 characters long), which may not be what you're looking for.
See this (Be aware, the color is changing, but because it's using the hex code :
var div = document.getElementById("full");
function getclockColor() {
var today = new Date();
var h = today.getHours().toString();
var m = today.getMinutes().toString();
var s = today.getSeconds().toString();
var color='#'+h+m+s;
return color;
}
function changeColor() {
console.log(getclockColor());
div.style.backgroundColor = getclockColor();
}
setInterval(changeColor, 1000);
body {
overflow: hidden;
margin: 0;
padding: 0;
}
#full {
position: absolute;
height: 100%;
width: 100%;
}
<div id="full"></div>
To fix the potential 0 padding issue, see below (Grabbed pad from this question):
var div = document.getElementById("full");
function pad(n, width, z) {
z = z || '0';
n = n + '';
return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}
function getclockColor() {
var today = new Date();
var h = today.getHours().toString();
var m = today.getMinutes().toString();
var s = today.getSeconds().toString();
var color='#'+pad(h,2)+pad(m,2)+pad(s,2);
return color;
}
function changeColor() {
console.log(getclockColor());
div.style.backgroundColor = getclockColor();
}
setInterval(changeColor, 1000);
body {
overflow: hidden;
margin: 0;
padding: 0;
}
#full {
position: absolute;
height: 100%;
width: 100%;
}
<div id="full"></div>

Related

Can't access the style using DOM [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 5 years ago.
For some reason, the error keeps being thrown at me whenever I hover over the selected element. It seems like every time I use the .style property, it gives me this error. The problem is how I'm accessing the CSS element using .style. Is there another way of doing it?
Uncaught TypeError: Cannot read property 'style' of undefined
var image = document.getElementsByClassName("image");
var move = document.getElementsByClassName("link");
var description = document.getElementsByClassName("description");
for(var i = 0; i < move.length; i++){
move[i].addEventListener("click", function(){
if (move[i].style.marginLeft === "500px") {
move[i].style.marginLeft = "0";
} else {
move[i].style.marginLeft = "500px";
}
})
};
for(var i = 0; i<description.length;i++){
image[i].addEventListener("mouseover", function(){
description[i].style.visibility = visible;
description[i].style.opacity = 0;
var last = +new Date();
var tick = function(){
despcription[i].style.opacity = +despcription[i].style.opacity + (new Date() - last)/700;
last = +new Date();
if (+despcription[i].style.opacity < 1) {
(window.requestAnimationFrame && requestAnimationFrame(tick)) || setTimeout(tick, 16);
}
};
tick();
});
}
You have a typo: despcription
despcription[i].style.opacity = +despcription[i].style.opacity + (new Date() - last)/700;
last = +new Date();
if (+despcription[i].style.opacity < 1) {
And I don't know if you are trying to do more than this, but are you attempting to fade in an image on hover? If so, then setting this in CSS works well:
EDIT: I updated the sample to show a title under the image when you hover over the image. The key is the ~ (sibling) selector right here:
.image:hover~.image-title {
opacity: 1;
}
It says when the user hovers over the image class, then select the sibling element with class of .image-title and set its opacity to 1.
.image {
background-image: url('https://amazingslider.com/wp-content/uploads/2012/12/dandelion.jpg');
height: 300px;
width: 300px;
background-size: cover;
background-position: center;
}
.image:hover~.image-title {
opacity: 1;
}
.image-title {
opacity: 0;
transition: opacity 1s ease;
display: inline-block;
width: 300px;
text-align: center;
margin: 0;
}
<h1>Hover Over Image</h1>
<div class="image"></div>
<h3 class="image-title">Image Title</h3>

How do I add class for time(clock)

I get date and clock.
var mydate = new Date();
var clock = tarih.getHours();
var minute = tarih.getMinutes();
And want this;
if (clock> 5) {
add this class, if have id "menu" = "menu_edit" (i dont know how can i do)
}
How can I do that?
If 'menu' is id of element:
document.querySelector('#menu').className += " menu_edit";
UPD:
According to your comment:
document.querySelector('.class1').className += ' class2';
Or if there are several elements:
var elems = document.querySelectorAll('.class1');
elems.forEach = [].forEach;
elems.forEach(function(el){
el.className += ' class2';
});
https://developer.mozilla.org/docs/Web/API/Document/querySelector - about function.
http://www.w3schools.com/cssref/css_selectors.asp - about selectors.
Maybe something like this. Please see the comments for an explanation.
checkout https://babeljs.io/ for info on compiling ES6 to ES5
const menu = document.querySelector('#menu')
const menuClasses = [
'menu--morning',
'menu--afternoon',
'menu--evening'
]
// helper function to toggle classes like a radio button
// this uses currying to lock in the classes and element, but
// allow us to change the active class dynamically
const toggleClasses = (classes, element) => clazz => {
element.classList.remove(...classes)
element.classList.add(clazz)
}
// create the toggle function and pass in the classes and the element
const toggleMenuClass = toggleClasses(menuClasses, menu)
// run a timer every n seconds
const timer = () => {
const date = new Date()
// I'm using seconds for the example as you will see the change
// but you should change this to hours
const second = date.getSeconds()
if (second < 20) {
toggleMenuClass('menu--morning')
}
else if (second < 40) {
toggleMenuClass('menu--afternoon')
}
else {
toggleMenuClass('menu--evening')
}
// just to show the current time for the example
menu.textContent = second
// call the timer function again after 500 milliseconds
setTimeout(timer, 500)
}
// init the timer on load
timer()
#menu {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
transition: 1s background;
font-size: 5em;
font-family: sans-serif;
color:#fff;
text-align: center;
line-height: 100vh;
}
#menu.menu--morning {
background: #AED6F1;
}
#menu.menu--afternoon {
background: #ABEBC6;
}
#menu.menu--evening {
background: #B95A75;
}
<div id="menu">clock</div>
Thanks everyone. I solved my problem with pHp.
Instead of adding class, i try take a different css page. Thanks for all things.
Have a nice day. :)
$clock = date('H');
if ($clock > 14) {
echo "<link rel='stylesheet' type='text/css' href='css/night.css'>";
}

Checking function for sliding puzzle javascript

I created a sliding puzzle with different formats like: 3x3, 3x4, 4x3 and 4x4. When you run my code you can see on the right side a selection box where you can choose the 4 formats. The slidingpuzzle is almost done. But I need a function which checks after every move if the puzzle is solved and if that is the case it should give out a line like "Congrantulations you solved it!" or "You won!". Any idea how to make that work?
In the javascript code you can see the first function loadFunc() is to replace every piece with the blank one and the functions after that are to select a format and change the format into it. The function Shiftpuzzlepieces makes it so that you can move each piece into the blank space. Function shuffle randomizes every pieces position. If you have any more question or understanding issues just feel free to ask in the comments. Many thanks in advance.
Since I don't have enough reputation I will post a link to the images here: http://imgur.com/a/2nMlt . These images are just placeholders right now.
Here is the jsfiddle:
http://jsfiddle.net/Cuttingtheaces/vkyxgwo6/19/
As always, there is a "hacky", easy way to do this, and then there is more elegant but one that requires significant changes to your code.
Hacky way
To accomplish this as fast and dirty as possible, I would go with parsing id-s of pieces to check if they are in correct order, because they have this handy pattern "position" + it's expected index or "blank":
function isFinished() {
var puzzleEl = document.getElementById('slidingpuzzleContainer').children[0];
// convert a live list of child elements into regular array
var pieces = [].slice.call(puzzleEl.children);
return pieces
.map(function (piece) {
return piece.id.substr(8); // strip "position" prefix
})
.every(function (id, index, arr) {
if (arr.length - 1 == index) {
// last peace, check if it's blank
return id == "blank";
}
// check that every piece has an index that matches its expected position
return index == parseInt(id);
});
}
Now we need to check it somewhere, and naturally the best place would be after each move, so shiftPuzzlepieces() should be updated to call isFinished() function, and show the finishing message if it returns true:
function shiftPuzzlepieces(el) {
// ...
if (isFinished()) {
alert("You won!");
}
}
And voilà: live version.
How would I implement this game
For me, the proper way of implementing this would be to track current positions of pieces in some data structure and check it in similar way, but without traversing DOM or checking node's id-s. Also, it would allow to implement something like React.js application: onclick handler would mutate current game's state and then just render it into the DOM.
Here how I would implement the game:
/**
* Provides an initial state of the game
* with default size 4x4
*/
function initialState() {
return {
x: 4,
y: 4,
started: false,
finished: false
};
}
/**
* Inits a game
*/
function initGame() {
var gameContainer = document.querySelector("#slidingpuzzleContainer");
var gameState = initialState();
initFormatControl(gameContainer, gameState);
initGameControls(gameContainer, gameState);
// kick-off rendering
render(gameContainer, gameState);
}
/**
* Handles clicks on the container element
*/
function initGameControls(gameContainer, gameState) {
gameContainer.addEventListener("click", function hanldeClick(event) {
if (!gameState.started || gameState.finished) {
// game didn't started yet or already finished, ignore clicks
return;
}
if (event.target.className.indexOf("piece") == -1) {
// click somewhere not on the piece (like, margins between them)
return;
}
// try to move piece somewhere
movePiece(gameState, parseInt(event.target.dataset.index));
// check if we're done here
checkFinish(gameState);
// render the state of game
render(gameContainer, gameState);
event.stopPropagation();
return false;
});
}
/**
* Checks whether game is finished
*/
function checkFinish(gameState) {
gameState.finished = gameState.pieces.every(function(id, index, arr) {
if (arr.length - 1 == index) {
// last peace, check if it's blank
return id == "blank";
}
// check that every piece has an index that matches its expected position
return index == id;
});
}
/**
* Moves target piece around if there's blank somewhere near it
*/
function movePiece(gameState, targetIndex) {
if (isBlank(targetIndex)) {
// ignore clicks on the "blank" piece
return;
}
var blankPiece = findBlankAround();
if (blankPiece == null) {
// nowhere to go :(
return;
}
swap(targetIndex, blankPiece);
function findBlankAround() {
var up = targetIndex - gameState.x;
if (targetIndex >= gameState.x && isBlank(up)) {
return up;
}
var down = targetIndex + gameState.x;
if (targetIndex < ((gameState.y - 1) * gameState.x) && isBlank(down)) {
return down;
}
var left = targetIndex - 1;
if ((targetIndex % gameState.x) > 0 && isBlank(left)) {
return left;
}
var right = targetIndex + 1;
if ((targetIndex % gameState.x) < (gameState.x - 1) && isBlank(right)) {
return right;
}
}
function isBlank(index) {
return gameState.pieces[index] == "blank";
}
function swap(i1, i2) {
var t = gameState.pieces[i1];
gameState.pieces[i1] = gameState.pieces[i2];
gameState.pieces[i2] = t;
}
}
/**
* Handles form for selecting and starting the game
*/
function initFormatControl(gameContainer, state) {
var formatContainer = document.querySelector("#formatContainer");
var formatSelect = formatContainer.querySelector("select");
var formatApply = formatContainer.querySelector("button");
formatSelect.addEventListener("change", function(event) {
formatApply.disabled = false;
});
formatContainer.addEventListener("submit", function(event) {
var rawValue = event.target.format.value;
var value = rawValue.split("x");
// update state
state.x = parseInt(value[0], 10);
state.y = parseInt(value[1], 10);
state.started = true;
state.pieces = generatePuzzle(state.x * state.y);
// render game
render(gameContainer, state);
event.preventDefault();
return false;
});
}
/**
* Renders game's state into container element
*/
function render(container, state) {
var numberOfPieces = state.x * state.y;
updateClass(container, state.x, state.y);
clear(container);
var containerHTML = "";
if (!state.started) {
for (var i = 0; i < numberOfPieces; i++) {
containerHTML += renderPiece("", i) + "\n";
}
} else if (state.finished) {
containerHTML = "<div class='congratulation'><h2 >You won!</h2><p>Press 'Play!' to start again.</p></div>";
} else {
containerHTML = state.pieces.map(renderPiece).join("\n");
}
container.innerHTML = containerHTML;
function renderPiece(id, index) {
return "<div class='piece' data-index='" + index + "'>" + id + "</div>";
}
function updateClass(container, x, y) {
container.className = "slidingpuzzleContainer" + x + "x" + y;
}
function clear(container) {
container.innerHTML = "";
}
}
/**
* Generates a shuffled array of id-s ready to be rendered
*/
function generatePuzzle(n) {
var pieces = ["blank"];
for (var i = 0; i < n - 1; i++) {
pieces.push(i);
}
return shuffleArray(pieces);
function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
}
body {
font-family: "Lucida Grande", "Lucida Sans Unicode", Verdana, Helvetica, Arial, sans-serif;
font-size: 12px;
color: #000;
}
#formatContainer {
position: absolute;
top: 50px;
left: 500px;
}
#formatContainer label {
display: inline-block;
max-width: 100%;
margin-bottom: 5px;
}
#formatContainer select {
display: block;
width: 100%;
margin-top: 10px;
margin-bottom: 10px;
}
#formatContainer button {
display: inline-block;
width: 100%;
}
.piece {
width: 96px;
height: 96px;
margin: 1px;
float: left;
border: 1px solid black;
}
.slidingpuzzleContainer3x3,
.slidingpuzzleContainer3x4,
.slidingpuzzleContainer4x3,
.slidingpuzzleContainer4x4 {
position: absolute;
top: 50px;
left: 50px;
border: 10px solid black;
}
.slidingpuzzleContainer3x3 {
width: 300px;
height: 300px;
}
.slidingpuzzleContainer3x4 {
width: 300px;
height: 400px;
}
.slidingpuzzleContainer4x3 {
width: 400px;
height: 300px;
}
.slidingpuzzleContainer4x4 {
width: 400px;
height: 400px;
}
.congratulation {
margin: 10px;
}
}
<body onload="initGame();">
<div id="slidingpuzzleContainer"></div>
<form id="formatContainer">
<label for="format">select format:</label>
<select name="format" id="format" size="1">
<option value="" selected="true" disabled="true"></option>
<option value="3x3">Format 3 x 3</option>
<option value="3x4">Format 3 x 4</option>
<option value="4x3">Format 4 x 3</option>
<option value="4x4">Format 4 x 4</option>
</select>
<button type="submit" disabled="true">Play!</button>
</form>
</body>
Here we have the initGame() function that starts everything. When called it will create an initial state of the game (we have default size and state properties to care about there), add listeners on the controls and call render() function with the current state.
initGameControls() sets up a listener for clicks on the field that will 1) call movePiece() which will try to move clicked piece on the blank spot if the former is somewhere around, 2) check if after move game is finished with checkFinish(), 3) call render() with updated state.
Now render() is a pretty simple function: it just gets the state and updates the DOM on the page accordingly.
Utility function initFormatControl() handles clicks and updates on the form for field size selection, and when the 'Play!' button is pressed will generate initial order of the pieces on the field and call render() with new state.
The main benefit of this approach is that almost all functions are decoupled from one another: you can tweak logic for finding blank space around target piece, to allow, for example, to swap pieces with adjacent ids, and even then functions for rendering, initialization and click handling will stay the same.
$(document).on('click','.puzzlepiece', function(){
var count = 0;
var imgarray = [];
var test =[0,1,2,3,4,5,6,7,8,'blank']
$('#slidingpuzzleContainer img').each(function(i){
var imgalt = $(this).attr('alt');
imgarray[i] = imgalt;
count++;
});
var is_same = (imgarray.length == test.length) && imgarray.every(function(element, index) {
return element === array2[index];
});
console.log(is_same); ///it will true if two array is same
});
try this... this is for only 3*3.. you pass the parameter and makethe array value as dynamically..

Custom audio player issues

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style type="text/CSS">
#custom{
font-family: monospace;
font-size: 16px;
max-width: 650px;
border-style: solid;
border-color: black;
border-width: 1px;
border-radius: 5px;
padding: 8px;
padding-bottom: 15px;
padding-left: 12px;
padding-right: 12px;
}
img{
margin-top: 3px;
float: left;
}
#bar, #currentTime, #duration, #skip{
display: inline-block;
}
#currentTime, #duration, #skip{
margin: 0px;
padding: 0px;
margin-top: 3px;
margin-left: 10px;
}
#bar{
margin-top: 10px;
height: 14px;
width: 400px;
background: lightgrey;
border-radius: 50px;
margin-left: 9px;
}
#slider{
height: 14px;
width: 15px;
background: black;
border-radius: 50px;
}
</style>
</head>
<body onLoad="count()">
<script type="text/javascript">
var track = 0;
function count(){
var music = document.getElementById("myAudio");
var duration = music.duration;
var durationInMins = Math.floor(duration/60);
var durationInSecs = Math.floor(duration-(durationInMins*60));
if(durationInSecs < 10){
var durationInSecs = "0" + durationInSecs;
}
if(durationInMins < 10){
var durationInMins = "0" + durationInMins;
}
document.getElementById("duration").innerHTML = durationInMins + ":" + durationInSecs;
var timer = setInterval(
function(){
var music = document.getElementById("myAudio");
var currentTime = music.currentTime;
if(currentTime > 60){
var min = Math.floor(currentTime/60);
var sec = Math.floor(currentTime-(min*60));
}else{
var min = "0";
var sec = Math.floor(music.currentTime); }
if(sec < 10){
var sec = "0" + sec;
}
if(min < 10){
var min = "0" + min;
}
document.getElementById("currentTime").innerHTML = min + ":" + sec; var percent = 100 * (music.currentTime/duration) - 2;
document.getElementById("slider").style.marginLeft=percent + "%";
}
, 1000);
}
function toggleP(){
var music = document.getElementById("myAudio");
if(music.paused == true){
music.play();
}else if(music.paused == false){
music.pause();
}
}
function skip(){
var trackList = ["http://fidelak.free.fr/reprises/The%20Doors%20-%20People%20are%20Strange.mp3", "http://mp3light.net/assets/songs/14000-14999/14781-december-1963-oh-what-a-night-four-seasons--1411568407.mp3"];
if(go == "back"){
track = track - 1;
}
if(go == "forward"){
track = track + 1;
}
var aa = clearInterval("timer");
var music = document.getElementById("myAudio");
music.pause();
music.src=trackList[track];
music.load();
var a = setTimeout(function(){music.play(); count();} , 6000);
}
</script>
<audio id="myAudio" src="http://fidelak.free.fr/reprises/The%20Doors%20-%20People%20are%20Strange.mp3">
</audio>
<br>
<div id="custom">
<img onClick="toggleP()" src="img/media-play-pause-resume.png" height="30px"/>
<p id="currentTime">00:00</p>
<div id="bar">
<div id="slider"></div>
</div>
<p id="duration">00:00</p>
<p id="skip"><strong><a onClick="go = 'back'; skip()"><<</a> <a onClick="go = 'forward'; skip()">>></a><strong></p>
</div>
</body>
Could anyone tell me why the song duration slider jumps forwards and backwards after you skip to the second song? And why the duration bar cannot be moved down with margin-top without moving everything with it. I just can't figure it out. Any help would be greatly appreciated, Thanks.
jsBin demo
Don't use inline JS in your HTML! Makes code hard to debug. Keep your logic away from your presentation/template.
To start from, how variables work?
Once you set a var, there's no need to instantiate the same var again using var inside your code. Simply use/modify it. So once you set at the top
function el(id){return document.getElementById(id);} // Helps get easily an element
var el_music = el("myAudio"), // see?
el_trackInfo= el("trackInfo"),
el_duration = el("duration"),
el_currTime = el("currentTime"),
el_slider = el("slider"),
el_prev = el("prev"), // assign ID to your prev/next buttons!
el_next = el("next"),
el_togg = el("toggle"),
currentTime,
trackList = [],
track = -1, // Later we'll set it to 0 index triggering auto start
totTrack = trackList.length;
...you're good to go. No more var statements further in your code.
You probably want to show some more info to the user.
A good way to store your data is to create Objects with the desired properties:
trackList = [
{
artist : "The Doors",
fileName : "People Are Strange",
file : "http://fidelak.free.fr/reprises/The%20Doors%20-%20People%20are%20Strange.mp3"
},
{
artist : "ACDC",
fileName : "Back In Black",
file : "http://upload.wikimedia.org/wikipedia/en/4/45/ACDC_-_Back_In_Black-sample.ogg"
},
{
artist : "Four Seasons",
fileName : "Oh What A Night",
file : "http://mp3light.net/assets/songs/14000-14999/14781-december-1963-oh-what-a-night-four-seasons--1411568407.mp3"
}
]
now you can not only get the desired audio path, but also show the user more info about a track.
Don't Repeat Yourself. Calculating times all over the place makes your code not modular but messy. Instead create a function that'll help you return the desired formatted time:
function getTime(t) { // `t` is some time value
var m = ~~(t / 60),
s = ~~(t % 60);
return (m<10?"0"+m:m) +':'+ (s<10?"0"+s:s); // returns i.e: "01:25"
}
Create a progress function like:
function progress() {
el_currTime.innerHTML = getTime(el_music.currentTime); // see how our getTime fn is used?
el_duration.innerHTML = getTime(el_music.duration);
el_slider.style.marginLeft = Math.floor(100/el_music.duration*el_music.currentTime) + "%";
}
than a play/pause one:
function playPause(){
var isPaused = el_music.paused;
el_music[isPaused ? "play" : "pause"]();
el_togg.innerHTML = isPaused ? "❚❚" : "►" ;
}
for the PREV/NEXT, assign IDs to your buttons id="prev" and id="next" and again create a function that will handle both click cases:
function skip(){ // This gets triggered by both prev / next buttons.
track = this.id==="next" ? ++track : --track; // Next clicked' increment, else decr.
track = track < 0 ? totTrack-1 : track%totTrack; // Allows you to loop infinitely the index
var trackToPlay = trackList[ track ]; // Get the Track Object "{}"
el_trackInfo.innerHTML = trackToPlay.artist+' '+trackToPlay.fileName;
el_music.src = trackToPlay.file;
el_music.addEventListener('canplaythrough', el_music.play);
}
Believe it or not - you're done!
Having all those nifty functions in place, what you need now is some event listeners:
el_prev.addEventListener("click", skip);
el_next.addEventListener("click", skip);
el_togg.addEventListener("click", playPause);
el_music.addEventListener("timeupdate", progress);
el_music.addEventListener("ended", playPause);
el_next.click(); // Auto Start playing!
Now you probably wonder where's your interval 1000 function gone? It's simply handled by el_music.addEventListener("timeupdate", progress);.
The skipping may be caused by the fact that the interval is never stopped, and is still running for the previous song.

javascript display numbers as picture with animation

I like to display some numbers as pictures. All numbers are included in one picture.
I started with creating a span for each number and each span get a different class so that I can change the picture for the correct number with the style attribute "background-position".
This is working for me. But now I like to add a little animation to this numbers like count up to the correct value. I can do this for one span (number) but how can I do this for all numbers?
HTML:
<style>
.digit0 { background-position: 0 0; }
.digit1 { background-position: 0 -120px; }
.digit2 { background-position: 0 -240px; }
.digit3 { background-position: 0 -360px; }
.digit4 { background-position: 0 -480px; }
.digit5 { background-position: 0 -600px; }
.digit6 { background-position: 0 -720px; }
.digit7 { background-position: 0 -840px; }
.digit8 { background-position: 0 -960px; }
.digit9 { background-position: 0 -1080px; }
</style>
</head>
<body>
<h1>Examples</h1>
<p>
<div id="number">here</div>
</p>
</body>
Javascript:
<script type="text/javascript">
$(document).ready(function(){
// Your code here
var dd = "5487";
dd = dd.replace(/(\d)/g, '<span class="digit0" id="count$1" style="display: inline-block; height: 20px; line-height: 40px; width: 14px; vertical-align: middle; text-align: center; font: 0/0 a; text-shadow: none; background-image: url(../src/jquery.counter-analog.png); color: transparent; margin: 0;"></span>');
$("#number").html(dd);
count = $("#count4").attr("id").replace("count", "").toString();
var i = 0;
setInterval(function() {
counter();
}, 100);
function counter() {
if(i < count) {
i++;
$("#count4").attr("class", "digit" + i + "");
}
}
});
</script>
This is not possible using pure Javascript.
What you're asking for will have to be performed server-side using something like PHP's GD.
Here's one way to do it. It certainly still has room for efficiency and legibility improvement, here and there (see edit history of this answer for one such improvement :) ). But it's a decent start imho:
// goal digits
var dd = '5487';
// separate digits
var digits = dd.split( '' );
// set some animation interval
var interval = 100;
// create spans for each digit,
// append to div#number and initialize animation
digits.forEach( function( value, index ) {
// create a span with initial conditions
var span = $( '<span>', {
'class': 'digit0',
'data': {
'current': 0,
'goal' : value
}
} );
// append span to the div#number
span.appendTo( $( 'div#number' ) );
// call countUp after interval multiplied by the index of this span
setTimeout( function() { countUp.call( span ); }, index * interval );
} );
// count animation function
function countUp()
{
// the current span we're dealing with
var span = this;
// the current value of the span
var current = span.data( 'current' );
// the end goal digit of this span
var goal = span.data( 'goal' );
// increment the digit, if we've not reached the goal yet
if( current < goal )
{
++current;
span.attr( 'class', 'digit' + current );
span.data( 'current', current );
// call countUp again after interval
setTimeout( function() { countUp.call( span ); }, interval );
}
}
See it in action on jsfiddle
To change the speed of the animation, alter the value of interval.
I've answered another similar question some days ago:
$.fn.increment = function (from, to, duration, easing, complete) {
var params = $.speed(duration, easing, complete);
return this.each(function(){
var self = this;
params.step = function(now) {
self.innerText = now << 0;
};
$({number: from}).animate({number: to}, params);
});
};
$('#count').increment(0, 1337);
Update
If you really want to use images, take this:
$.fn.increment = function (x, y, from, to, duration, easing, complete) {
var params = $.speed(duration, easing, complete);
return this.each(function(){
var self = this;
params.step = function(now) {
self.style.backgroundPosition = x * Math.round(now) + 'px ' + y * Math.round(now) + 'px';
};
$({number: from}).animate({number: to}, params);
});
};
$('#count').increment(0, 120, 9);

Categories