jquery recursive function to non-recursive function - javascript

i am sorry this question might be one of those "stupid questions". I have this round progressbar that works perfectly, when i click the button named "animateButton". But I want to start the progressbar with a function call, but the function does not have a name, because its recursive in the progressbar, i guess. How do I make the function to start the progress when i call a function like this startIt()?.
$(function() {
var $topLoader = $("#topLoader").percentageLoader({width: 60, height: 60, controllable : true, progress : 0.0, onProgressUpdate : function(val) {
$topLoader.setValue(Math.round(val * 100.0));
}});
var topLoaderRunning = false;
$("#animateButton").click(function() {
if (topLoaderRunning) {
return;
}
topLoaderRunning = true;
$topLoader.setProgress(0);
$topLoader.setValue('0kb');
var kb = 0;
var totalKb = 500; //100=2.7 1000=27
var animateFunc = function() {
kb += 1;
$topLoader.setProgress(kb / totalKb);
$topLoader.setValue(kb.toString() + 'kb');
if (kb < totalKb) {
setTimeout(animateFunc, 25);
} else {
topLoaderRunning = false;
}
}
setTimeout(animateFunc, 25);
});
});
I got it working as easy as this:
startLoader = function() {
var $topLoader = $("#topLoader").percentageLoader({width: 60, height: 60, controllable : true, progress : 0.0, onProgressUpdate : function(val) {
$topLoader.setValue(Math.round(val * 100.0));
}});
var topLoaderRunning = false;
if (topLoaderRunning) {
return;
}
topLoaderRunning = true;
$topLoader.setProgress(0);
$topLoader.setValue('0kb');
var kb = 0;
var totalKb = 500; //100=2.7 1000=27
var animateFunc = function() {
kb += 1;
$topLoader.setProgress(kb / totalKb);
$topLoader.setValue(kb.toString() + 'kb');
if (kb < totalKb) {
setTimeout(animateFunc, 25);
} else {
topLoaderRunning = false;
}
}
setTimeout(animateFunc, 25);
};

You already have all the pieces, you just need to reorder them a bit. Give your function a name, then assign that name to the click event. Then you can explicitly call the function by name at the end.
Untested code below, but I've used this principle many times.
$(function() {
var $topLoader = $("#topLoader").percentageLoader({width: 60, height: 60, controllable : true, progress : 0.0, onProgressUpdate : function(val) {
$topLoader.setValue(Math.round(val * 100.0));
}});
var topLoaderRunning = false;
var startIt = function() {
if (topLoaderRunning) {
return;
}
topLoaderRunning = true;
$topLoader.setProgress(0);
$topLoader.setValue('0kb');
var kb = 0;
var totalKb = 500; //100=2.7 1000=27
var animateFunc = function() {
kb += 1;
$topLoader.setProgress(kb / totalKb);
$topLoader.setValue(kb.toString() + 'kb');
if (kb < totalKb) {
setTimeout(animateFunc, 25);
} else {
topLoaderRunning = false;
}
}
setTimeout(animateFunc, 25);
};
$("#animateButton").click(startIt);
startIt();
});

If I understand your question correctly, you want something like this:
$(function() {
var $topLoader = $("#topLoader").percentageLoader({width: 60, height: 60, controllable : true, progress : 0.0, onProgressUpdate : function(val) {
$topLoader.setValue(Math.round(val * 100.0));
}});
var topLoaderRunning = false;
var startIt = function() {
// function body...
};
$("#animateButton").click(startIt);
});
You can always assign functions to variables if you need to access them by name.

Related

How to trigger createjs animation on slick slider afterchange callback?

I am using slick carousel slider which has 5 slides, each slide should trigger an animation after it gets displayed on the page.
An animator has created an animation using Adobe Animate CC and exported the animation in createjs format so it is compatible with html5.
If I try to call the animation on afterchange I get an error:
TypeError: lib.FlowerGrowTemplate is not a constructor
See the comment below for where the error is happening:
/*The error is pointing to here*/
Adobe Animate CC generated javascript code:
(function (cjs, an) {
var p; // shortcut to reference prototypes
var lib={};var ss={};var img={};
lib.ssMetadata = [];
// symbols:
// helper functions:
function mc_symbol_clone() {
var clone = this._cloneProps(new this.constructor(this.mode, this.startPosition, this.loop));
clone.gotoAndStop(this.currentFrame);
clone.paused = this.paused;
clone.framerate = this.framerate;
return clone;
}
function getMCSymbolPrototype(symbol, nominalBounds, frameBounds) {
var prototype = cjs.extend(symbol, cjs.MovieClip);
prototype.clone = mc_symbol_clone;
prototype.nominalBounds = nominalBounds;
prototype.frameBounds = frameBounds;
return prototype;
}
.....
})(createjs = createjs||{}, AdobeAn = AdobeAn||{});
var createjs, AdobeAn;
var graphic_canvas_1, graphic_stage_1, graphic_exportRoot_1, graphic_container_1, graphic_dom_overlay_container_1, graphic_fnStartAnimation_1;
function graphic_init_1() {
graphic_canvas_1 = document.getElementById("graphic_canvas");
graphic_container_1 = document.getElementById("graphic_container");
graphic_dom_overlay_container_1 = document.getElementById("graphic_dom_overlay_container");
var comp=AdobeAn.getComposition("AD6FD640782B2A4DAD43D647860AC61B");
var lib=comp.getLibrary();
graphic_handleComplete_1({},comp);
}
function graphic_handleComplete_1(evt,comp) {
//This function is always called, irrespective of the content. You can use the variable "stage" after it is created in token create_stage.
var lib=comp.getLibrary();
var ss=comp.getSpriteSheet();
graphic_exportRoot_1 = new lib.FlowerGrowTemplate(); /*The error is pointing to here*/
graphic_stage_1 = new lib.Stage(graphic_canvas_1);
//Registers the "tick" event listener.
graphic_fnStartAnimation_1 = function() {
graphic_stage_1.addChild(graphic_exportRoot_1);
createjs.Ticker.setFPS(lib.properties.fps);
createjs.Ticker.addEventListener("tick", graphic_stage_1)
graphic_stage_1.addEventListener("tick", graphic_handleTick_1)
function graphic_getProjectionMatrix_1(container, totalDepth) {
var focalLength = 528.25;
var projectionCenter = { x : lib.properties.width/2, y : lib.properties.height/2 };
var scale = (totalDepth + focalLength)/focalLength;
var scaleMat = new createjs.Matrix2D;
scaleMat.a = 1/scale;
scaleMat.d = 1/scale;
var projMat = new createjs.Matrix2D;
projMat.tx = -projectionCenter.x;
projMat.ty = -projectionCenter.y;
projMat = projMat.prependMatrix(scaleMat);
projMat.tx += projectionCenter.x;
projMat.ty += projectionCenter.y;
return projMat;
}
function graphic_handleTick_1(event) {
var cameraInstance = graphic_exportRoot_1.___camera___instance;
if(cameraInstance !== undefined && cameraInstance.pinToObject !== undefined)
{
cameraInstance.x = cameraInstance.pinToObject.x + cameraInstance.pinToObject.pinOffsetX;
cameraInstance.y = cameraInstance.pinToObject.y + cameraInstance.pinToObject.pinOffsetY;
if(cameraInstance.pinToObject.parent !== undefined && cameraInstance.pinToObject.parent.depth !== undefined)
cameraInstance.depth = cameraInstance.pinToObject.parent.depth + cameraInstance.pinToObject.pinOffsetZ;
}
graphic_applyLayerZDepth_1(graphic_exportRoot_1);
}
function graphic_applyLayerZDepth_1(parent)
{
var cameraInstance = parent.___camera___instance;
var focalLength = 528.25;
var projectionCenter = { 'x' : 0, 'y' : 0};
if(parent === graphic_exportRoot_1)
{
var stageCenter = { 'x' : lib.properties.width/2, 'y' : lib.properties.height/2 };
projectionCenter.x = stageCenter.x;
projectionCenter.y = stageCenter.y;
}
for(child in parent.children)
{
var layerObj = parent.children[child];
if(layerObj == cameraInstance)
continue;
graphic_applyLayerZDepth_1(layerObj, cameraInstance);
if(layerObj.layerDepth === undefined)
continue;
if(layerObj.currentFrame != layerObj.parent.currentFrame)
{
layerObj.gotoAndPlay(layerObj.parent.currentFrame);
}
var matToApply = new createjs.Matrix2D;
var cameraMat = new createjs.Matrix2D;
var totalDepth = layerObj.layerDepth ? layerObj.layerDepth : 0;
var cameraDepth = 0;
if(cameraInstance && !layerObj.isAttachedToCamera)
{
var mat = cameraInstance.getMatrix();
mat.tx -= projectionCenter.x;
mat.ty -= projectionCenter.y;
cameraMat = mat.invert();
cameraMat.prependTransform(projectionCenter.x, projectionCenter.y, 1, 1, 0, 0, 0, 0, 0);
cameraMat.appendTransform(-projectionCenter.x, -projectionCenter.y, 1, 1, 0, 0, 0, 0, 0);
if(cameraInstance.depth)
cameraDepth = cameraInstance.depth;
}
if(layerObj.depth)
{
totalDepth = layerObj.depth;
}
//Offset by camera depth
totalDepth -= cameraDepth;
if(totalDepth < -focalLength)
{
matToApply.a = 0;
matToApply.d = 0;
}
else
{
if(layerObj.layerDepth)
{
var sizeLockedMat = graphic_getProjectionMatrix_1(parent, layerObj.layerDepth);
if(sizeLockedMat)
{
sizeLockedMat.invert();
matToApply.prependMatrix(sizeLockedMat);
}
}
matToApply.prependMatrix(cameraMat);
var projMat = graphic_getProjectionMatrix_1(parent, totalDepth);
if(projMat)
{
matToApply.prependMatrix(projMat);
}
}
layerObj.transformMatrix = matToApply;
}
}
}
//Code to support hidpi screens and responsive scaling.
function graphic_makeResponsive_1(isResp, respDim, isScale, scaleType) {
var lastW, lastH, lastS=1;
window.addEventListener('resize', graphic_resizeCanvas_1);
graphic_resizeCanvas_1();
function graphic_resizeCanvas_1() {
var w = lib.properties.width, h = lib.properties.height;
var iw = window.innerWidth, ih=window.innerHeight;
var pRatio = window.devicePixelRatio || 1, xRatio=iw/w, yRatio=ih/h, sRatio=1;
if(isResp) {
if((respDim=='width'&&lastW==iw) || (respDim=='height'&&lastH==ih)) {
sRatio = lastS;
}
else if(!isScale) {
if(iw<w || ih<h)
sRatio = Math.min(xRatio, yRatio);
}
else if(scaleType==1) {
sRatio = Math.min(xRatio, yRatio);
}
else if(scaleType==2) {
sRatio = Math.max(xRatio, yRatio);
}
}
graphic_canvas_1.width = w*pRatio*sRatio;
graphic_canvas_1.height = h*pRatio*sRatio;
graphic_canvas_1.style.width = graphic_dom_overlay_container_1.style.width = graphic_container_1.style.width = w*sRatio+'px';
graphic_canvas_1.style.height = graphic_container_1.style.height = graphic_dom_overlay_container_1.style.height = h*sRatio+'px';
graphic_stage_1.scaleX = pRatio*sRatio;
graphic_stage_1.scaleY = pRatio*sRatio;
lastW = iw; lastH = ih; lastS = sRatio;
graphic_stage_1.tickOnUpdate = false;
graphic_stage_1.update();
graphic_stage_1.tickOnUpdate = true;
}
}
graphic_makeResponsive_1(false,'both',false,1);
AdobeAn.compositionLoaded(lib.properties.id);
graphic_fnStartAnimation_1();
}
My javascript code:
(function($){
$('.custom-graphic-slider .slider').slick({
slidesToShow: 1,
slidesToScroll: 1,
arrows: false,
dots: true,
fade: true,
});
$('.custom-graphic-slider .slider').on('afterChange', function(event, slick, currentSlide){
graphic_init_1();
});
})(jQuery);
I hope everything makes sense

Combining two Javascript functions to one window.onload not working

I have two functions that I want to run on window.onload event but only the last function seems to work so far. One function is for an image slider and the other one retrieves data from a google spreadsheet cell.
function fun1() { //image slider
var ul;
var li_items;
var imageNumber;
var imageWidth;
var prev, next;
var currentPostion = 0;
var currentImage = 0;
function init() {
ul = document.getElementById('image_slider');
li_items = ul.children;
imageNumber = li_items.length;
imageWidth = li_items[0].children[0].clientWidth;
ul.style.width = parseInt(imageWidth * imageNumber) + 'px';
prev = document.getElementById("prev");
next = document.getElementById("next");
prev.onclick = function() {
onClickPrev();
};
next.onclick = function() {
onClickNext();
};
}
function animate(opts) {
var start = new Date;
var id = setInterval(function() {
var timePassed = new Date - start;
var progress = timePassed / opts.duration;
if (progress > 1) {
progress = 1;
}
var delta = opts.delta(progress);
opts.step(delta);
if (progress == 1) {
clearInterval(id);
opts.callback();
}
}, opts.delay || 17);
}
function slideTo(imageToGo) {
var direction;
var numOfImageToGo = Math.abs(imageToGo - currentImage);
direction = currentImage > imageToGo ? 1 : -1;
currentPostion = -1 * currentImage * imageWidth;
var opts = {
duration: 1000,
delta: function(p) {
return p;
},
step: function(delta) {
ul.style.left = parseInt(currentPostion + direction * delta * imageWidth * numOfImageToGo) + 'px';
},
callback: function() {
currentImage = imageToGo;
}
};
animate(opts);
}
function onClickPrev() {
if (currentImage == 0) {
slideTo(imageNumber - 1);
} else {
slideTo(currentImage - 1);
}
}
function onClickNext() {
if (currentImage == imageNumber - 1) {
slideTo(0);
} else {
slideTo(currentImage + 1);
}
}
}
function fun2() {
// Google spreadsheet js
google.load('visualization', '1', {
callback: function() {
var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1sA7M5kG6Xo8YScD1Df38PIA_G0bvhGRdqoExXg0KJTs/gviz/tq?tqx=out:html&tq?gid=0&headers=0&range=A1:C');
query.send(displayData);
}
});
function displayData(response) {
numRows = response.getDataTable().getValue(0, 0);
document.getElementById('data').innerHTML = numRows;
}
}
var addFunctionOnWindowLoad = function(callback) {
if (window.addEventListener) {
window.addEventListener('load', callback, false);
} else {
window.attachEvent('onload', callback);
}
}
addFunctionOnWindowLoad(fun1);
addFunctionOnWindowLoad(fun2);
This is the answer I've tried link but I can't seem to figure out where I'm going wrong.
This is what I ended up doing, and now all the functions work.
var ul;
var li_items;
var imageNumber;
var imageWidth;
var prev, next;
var currentPostion = 0;
var currentImage = 0;
function init() {
ul = document.getElementById('image_slider');
li_items = ul.children;
imageNumber = li_items.length;
imageWidth = li_items[0].children[0].clientWidth;
ul.style.width = parseInt(imageWidth * imageNumber) + 'px';
prev = document.getElementById("prev");
next = document.getElementById("next");
prev.onclick = function() {
onClickPrev();
};
next.onclick = function() {
onClickNext();
};
}
function animate(opts) {
var start = (new Date());
var id = setInterval(function() {
var timePassed = (new Date()) - start;
var progress = timePassed / opts.duration;
if (progress > 1) {
progress = 1;
}
var delta = opts.delta(progress);
opts.step(delta);
if (progress == 1) {
clearInterval(id);
opts.callback();
}
}, opts.delay || 17);
//return id;
}
function slideTo(imageToGo) {
var direction;
var numOfImageToGo = Math.abs(imageToGo - currentImage);
// slide toward left
direction = currentImage > imageToGo ? 1 : -1;
currentPostion = -1 * currentImage * imageWidth;
var opts = {
duration: 1000,
delta: function(p) {
return p;
},
step: function(delta) {
ul.style.left = parseInt(currentPostion + direction * delta * imageWidth * numOfImageToGo) + 'px';
},
callback: function() {
currentImage = imageToGo;
}
};
animate(opts);
}
function onClickPrev() {
if (currentImage === 0) {
slideTo(imageNumber - 1);
} else {
slideTo(currentImage - 1);
}
}
function onClickNext() {
if (currentImage == imageNumber - 1) {
slideTo(0);
} else {
slideTo(currentImage + 1);
}
}
window.onload = init;
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
function fun2() {
// Google spreadsheet js
google.load('visualization', '1', {
callback: function() {
var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1sA7M5kG6Xo8YScD1Df38PIA_G0bvhGRdqoExXg0KJTs/gviz/tq?tqx=out:html&tq?gid=0&headers=0&range=A1:C');
query.send(displayData);
}
});
function displayData(response) {
numRows = response.getDataTable().getValue(0, 0);
document.getElementById('data').innerHTML = numRows;
}
}
addLoadEvent(fun2);
addLoadEvent(function() {
});
I found this function a while ago and believe it or not, I still need to use it every so often. addEventLoad() Just call addEventLoad while passing the function to load.
"The way this works is relatively simple: if window.onload has not already been assigned a function, the function passed to addLoadEvent is simply assigned to window.onload. If window.onload has already been set, a brand new function is created which first calls the original onload handler, then calls the new handler afterwards."
This snippet will load 3 functions on window.onload
Snippet
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
function alert1() {
alert("First Function Loaded");
}
function alert2() {
alert("Second Function Loaded");
}
function alert3(str) {
alert("Third Function Loaded; Msg: " + str);
}
addLoadEvent(alert1);
addLoadEvent(alert2);
addLoadEvent(function() {
alert3("This works");
});
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

Toggle class on HTML element without jQuery

I have a section on my website which holds all the content, but I want a "sidebar" with hidden content to smoothly appear from the left at the push of an external button.
CSS transitions can handle the smoothness no problem, and jQuery toggle() can switch between classes to move the hidden div in and out of the screen.
How can I get the same effect without using jQuery?
You can toggle classes using the classList.toggle() function:
var element = document.getElementById('sidebar');
var trigger = document.getElementById('js-toggle-sidebar'); // or whatever triggers the toggle
trigger.addEventListener('click', function(e) {
e.preventDefault();
element.classList.toggle('sidebar-active'); // or whatever your active class is
});
That should do everything you need - if you have more than one trigger I'd recommend using document.querySelectorAll(selector) instead.
You can implement it only by CSS3:
<label for="showblock">Show Block</label>
<input type="checkbox" id="showblock" />
<div id="block">
Hello World
</div>
And the CSS part:
#block {
background: yellow;
height: 0;
overflow: hidden;
transition: height 300ms linear;
}
label {
cursor: pointer;
}
#showblock {
display: none;
}
#showblock:checked + #block {
height: 40px;
}
The magic is the hidden checkbox and the :checked selector in CSS.
Working jsFiddle Demo.
HTML ONLY
You can use <summary>. The following code doesn't have any dependency.
No JavaScript, CSS at all, HTML only.
<div class="bd-example">
<details open="">
<summary>Some details</summary>
<p>More info about the details.</p>
</details>
<details>
<summary>Even more details</summary>
<p>Here are even more details about the details.</p>
</details>
</div>
For more detail, go to MDN official docs.
you can get any element by id with javascript (no jquery) and the class is an attribute :
element.className
so have this as a function:
UPDATE:
since this is becoming a somewhat popular I updated the function to make it better.
function toggleClass(element, toggleClass){
var currentClass = element.className || '';
var newClass;
if(currentClass.split(' ').indexOf(toggleClass) > -1){ //has class
newClass = currentClass.replace(new RegExp('\\b'+toggleClass+'\\b','g'), '')
}else{
newClass = currentClass + ' ' + toggleClass;
}
element.className = newClass.trim();
}
function init() {
animateCSS(document.getElementById("slide"), 250, {
left: function (timePercent, frame) {
var endPoint = 128,
startPoint = 0,
pathLength = endPoint - startPoint,
base = 64, //slope of the curve
currentPos = Math.floor(startPoint + (Math.pow(base, timePercent) - 1) / (base - 1) * pathLength);
return currentPos + "px";
}
}, function (element) {
element.style.left = "128px";
});
};
var JobType = function () {
if (!(this instanceof JobType)) {
return new JobType(arguments[0]);
};
var arg = arguments[0];
this.fn = arg["fn"];
this.delay = arg["delay"];
this.startTime = arg["startTime"];
this.comment = arg["comment"];
this.elapsed = 0;
};
function JobManager() {
if (!(this instanceof JobManager)) {
return new JobManager();
};
var instance;
JobManager = function () {
return instance;
};
JobManager.prototype = this;
instance = new JobManager();
instance.constructor = JobManager;
var jobQueue = [];
var startedFlag = false;
var inProcess = false;
var currentJob = null;
var timerID = -1;
var start = function () {
if (jobQueue.length) {
startedFlag = true;
currentJob = jobQueue.shift();
var startOver = currentJob.delay - ((new Date()).getTime() - currentJob.startTime);
timerID = setTimeout(function () {
inProcess = true;
currentJob.fn();
if (jobQueue.length) {
try {
while ((jobQueue[0].delay - ((new Date()).getTime() - currentJob.startTime)) <= 0) {
currentJob = jobQueue.shift();
currentJob.fn();
};
}
catch (e) { };
}
inProcess = false;
start();
}, (startOver > 0 ? startOver : 0));
}
else {
startedFlag = false;
timerID = -1;
};
};
instance.add = function (newJob) {
if (newJob instanceof JobType) {
stopCurrent();
var jobQueueLength = jobQueue.length;
if (!jobQueueLength) {
jobQueue.push(newJob);
}
else {
var currentTime = (new Date()).getTime(),
insertedFlag = false;
for (var i = 0; i < jobQueueLength; i++) {
var tempJob = jobQueue[i],
tempJobElapsed = currentTime - tempJob["startTime"],
tempJobDelay = tempJob["delay"] - tempJobElapsed;
tempJob["elapsed"] = tempJobElapsed;
if (newJob["delay"] <= tempJobDelay) {
if (!insertedFlag) {
jobQueue.splice(i, 0, newJob);
insertedFlag = true;
}
};
if (i === (jobQueueLength - 1)) {
if (!insertedFlag) {
jobQueue.push(newJob);
insertedFlag = true;
}
}
};
};
if ((!startedFlag) && (!inProcess)) {
start();
};
return true;
}
else {
return false;
};
};
var stopCurrent = function () {
if (timerID >= 0) {
if (!inProcess) {
clearTimeout(timerID);
timerID = -1;
if (currentJob) {
jobQueue.unshift(currentJob);
};
};
startedFlag = false;
};
};
return instance;
};
function animateCSS(element, duration, animation, whendone) {
var frame = 0,
elapsedTime = 0,
timePercent = 0,
startTime = new Date().getTime(),
endTime = startTime + duration,
fps = 0,
averageRenderTime = 1000,
normalRenderTime = 1000 / 25,
myJobManager = JobManager();
var inQueue = myJobManager.add(JobType({
"fn": displayNextFrame,
"delay": 0,
"startTime": (new Date).getTime(),
"comment": "start new animation"
}));
function playFrame() {
for (var cssprop in animation) {
try {
element.style[cssprop] = animation[cssprop].call(element, timePercent, frame);
} catch (e) { }
};
};
function displayNextFrame() {
elapsedTime = (new Date().getTime()) - startTime;
timePercent = elapsedTime / duration;
if (elapsedTime >= duration) {
playFrame();
if (whendone) {
whendone(element);
};
return;
};
playFrame();
frame++;
averageRenderTime = elapsedTime / frame;
fps = 1000 / averageRenderTime;
inQueue = myJobManager.add(JobType({
"fn": displayNextFrame,
"delay": (fps < 15 ? 0 : normalRenderTime - averageRenderTime),
"startTime": (new Date).getTime(),
"comment": frame
}));
}
};
(function () {
if (this.addEventListener) {
this.addEventListener("load", init, false)
}
else {
window.onload = init;
}
}());
// By Plain Javascript
// this code will work on most of browsers.
function hasClass(ele, clsName) {
var el = ele.className;
el = el.split(' ');
if(el.indexOf(clsName) > -1){
var cIndex = el.indexOf(clsName);
el.splice(cIndex, 1);
ele.className = " ";
el.forEach(function(item, index){
ele.className += " " + item;
})
}
else {
el.push(clsName);
ele.className = " ";
el.forEach(function(item, index){
ele.className += " " + item;
})
}
}
var btn = document.getElementById('btn');
var ele = document.getElementById('temp');
btn.addEventListener('click', function(){
hasClass(ele, 'active')
})
I did not test but the code below should work.
<script>
function toggleClass(){
var element = document.getElementById("a");
element.classList.toggle("b");
}
document.getElementById("c").addEventListener('click', toggleClass )
</script>

Converting jquery to javascript progress bar

Please help me convert this JQuery to Javascript progress bar script
var generateButton = document.getElementById("generate");
if (generateButton.addEventListener) {
generateButton.addEventListener("click", random, false);
}
else if (generateButton.attachEvent) {
generateButton.attachEvent('onclick', random);
}
function random(e) {
setTimeout(function(){
$('.progress .bar').each(function() {
var me = $(this);
var perc = me.attr("data-percentage");
//TODO: left and right text handling
var current_perc = 0;
var progress = setInterval(function() {
if (current_perc>=perc) {
clearInterval(progress);
} else {
current_perc +=1;
me.css('width', (current_perc)+'%');
}
me.text((current_perc)+'%');
}, 50);
});
},300);
var num = Math.random();
var greetingString = num;
document.getElementById("rslt").innerText = greetingString;
}
Here is the Live version: http://jsfiddle.net/chjjK/9/
Pretty easy actually, use document.getElementsByClassName and a for loop to replace the each:
var bar = document.getElementsByClassName("bar");
for (var i = 0; i < bar.length; i++) {
var me = bar[i];
var perc = me.getAttribute("data-percentage");
var current_perc = 0;
var progress = setInterval(function() {
if (current_perc>=perc) {
clearInterval(progress);
} else {
current_perc +=1;
me.style.width = current_perc+'%';
}
me.innerHTML = ((current_perc)+'%');
}, 50);
}
}, 300);
Demo: http://jsfiddle.net/chjjK/13/

Set and Clear Interval turns into multiple Interval

I am trying to develope a slider, which change every 5 seconds if the user doens´t hit the back- or forward-button.
But if he (the user) does, the interval fires multiple times... why?
I save the Interval in a variable and clear this variable so i don´t know why this dont work... but see yourself:
jQuery.fn.extend({
wrGallery: function() {
return this.each(function() {
// config
var wrClassActive = 'galerie_active';
var wrTime = 5000;
// wrAutomaticDirection gibt an, in welche Richtung
// die Gallerie bei automatischem Wechsel wechseln soll (True = vorwärts/rechts)
var wrAutomaticDirection = true;
var wr = jQuery(this);
var wrGalleryContents = wr.find('.galerie_content');
var wrGalleryContentsFirst = wr.find('.galerie_content:first-child');
var wrBtnBack = wr.find('#galerie_backward');
var wrBtnFor = wr.find('#galerie_forward');
var wrTimer = 0;
var wrI = 0;
var wrOldActiveID = 0;
var wrInit = function() {
wrGalleryContents.each(function() {
wrI++;
jQuery(this).attr('id', wrI);
jQuery(this).css({
display: 'none',
opacity: 0
})
})
wrGalleryContentsFirst.css({
display: 'block',
opacity: 1
})
wrGalleryContentsFirst.addClass('galerie_active')
wrStartTimer();
}
var wrStartTimer = function() {
wrTimer = setInterval(function() {
wrChange(wrAutomaticDirection);
}, wrTime)
}
var wrStoppTimer = function() {
clearInterval(wrTimer);
wrTimer = 0;
}
var wrBackground = function(wrDirection) {
wrOldActiveID = wr.find('.' + wrClassActive).attr('id');
wr.find('.' + wrClassActive).removeClass(wrClassActive);
if (wrDirection) {
wrOldActiveID++;
if (wrOldActiveID <= wrI) {
wr.find('#' + wrOldActiveID).addClass(wrClassActive);
} else {
wr.find('#1').addClass(wrClassActive);
}
} else {
wrOldActiveID--;
if (wrOldActiveID <= wrI) {
wr.find('#' + wrOldActiveID).addClass(wrClassActive);
} else {
wr.find('#3').addClass(wrClassActive);
}
}
}
var wrAnimate = function(wrDirection) {
wrGalleryContents.stop().animate({
opacity: 0
}, 500);
wr.find('.' + wrClassActive).css({
display: 'block'
})
wr.find('.' + wrClassActive).stop().animate({
opacity: 1
}, 500);
}
var wrChange = function(wrDirection) {
wrBackground(wrDirection);
wrAnimate(wrDirection);
}
wr.on('mouseenter', function() {
wrStoppTimer();
});
wr.on('mouseleave', function() {
wrStartTimer();
});
wrBtnBack.on('click', function() {
wrStoppTimer();
wrStartTimer();
wrChange(false);
});
wrBtnFor.on('click', function() {
wrStoppTimer();
wrStartTimer();
wrChange(true);
});
wrInit();
});
}
});
Thanks for reading ;-)
Add a wrStoppTimer() call at the beginning of wrStartTimer:
var wrStartTimer = function() {
wrStoppTimer();
wrTimer = setInterval(function() {
wrChange(wrAutomaticDirection);
}, wrTime)
};
Also in the two click functions you have:
wrStoppTimer();
wrStartTimer();
you can remove that wrStoppTimer() call since wrStartTimer() will call it for you now.
One other thing: if you define functions the way you're doing with var name = function() { ... } you should put a semicolon after the closing } as in the updated code above.

Categories

Resources