javascript slideshow without jquery - javascript

I cant find an example of what I am looking for -
I need a javascript slideshow that works WITHOUT jquery.
What the slideshow needs to do is display images, one by one (it would be nice if there would be a fading animation), and each image would be a link to another page. It is important that jquery is not used, because I am having some problems with that. I dont want any controls such as pause next... or any captions. Just <a> <img/> </a>

<!DOCTYPE html>
<html lang="en-US">
<head>
<title>JavaScript Fade - Brugbart Example</title>
<style type="text/css">
#Slideshow {
opacity: 1.0; /* CSS3 */
-moz-opacity: 1.0; /* Older versions of Firefox */
-khtml-opacity: 1.0; /* Older versions of Safari */
filter: alpha(opacity=100); /* Internet Explorer */
}
#Slideshow div {display:none;}
#Slideshow #slice1 {display:block;}
div{font-family: arial, sans-serif}
div{font-size:50px}
</style>
</head>
<body>
<div id="Basement" style="width:90%;margin:auto;">
<div id="Slideshow">
<div id="slice1">111111
</div>
<div id="slice2">222222
</div>
<div id="slice3">333333
</div>
</div>
</div>
<script type="text/javascript">
/* Creted with a reference from http://brugbart.com/slideshow-fade-javascript */
var duration = 250; /* fade duration in millisecond */
var hiddentime = 250; /* time to stay hidden */
var showtime = 1000; /* time to stay visible */
var active = 0 /* Used to check if fade is active */
var iEcount = 0 /* Element Counter */
var element = document.getElementById("Slideshow");
var iEarray = element.getElementsByTagName('div');
var iEtotal = iEarray.length;
StartFade();
function StartFade()
{
iEcount = 1;
setTimeout("FadeOut()", showtime);
}
function FadeOut()
{
for (i = 0; i <= 1; i += 0.01)
{
setTimeout("SetOpa(" + (1 - i) +")", i * duration);
}
setTimeout("FadeIn()", (duration + hiddentime));
}
function FadeIn()
{
for (i = 0; i <= 1; i += 0.01)
{
setTimeout("SetOpa(" + i +")", i * duration);
}
if (iEcount == iEtotal)
{
iEcount = 1
document.getElementById("slice" + iEcount).style.display = "block";
document.getElementById("slice" + iEtotal).style.display = "none";
}
else
{
document.getElementById("slice" + (iEcount + 1)).style.display = "block";
document.getElementById("slice" + iEcount).style.display = "none";
iEcount = iEcount+1
}
setTimeout("FadeOut()", (duration + showtime));
}
function SetOpa(Opa)
{
element.style.opacity = Opa;
element.style.MozOpacity = Opa;
element.style.KhtmlOpacity = Opa;
element.style.WebkitOpacity = Opa;
element.style.KhtmlOpacity = Opa;
element.style.MsOpacity = Opa;
element.style.width = "500px";
element.style.filter = 'alpha(opacity=' + (Opa * 100) + ');';
}
</script>

I would look at the answers here posted May 25, 2012. Similar questions have been asked many times. It helps to search for answers that have been already answered.
I have currently implemented just what you are trying to do. Very similar to what is in the post I linked to.

Related

Ascii Art Animation in Browser

I want to animate Ascii Art in the Browser.
The Ascii Art should be loaded via a text file. There are many libraries which convert but I have found none, which actually animates it.
By animation I mean a typewriter animation that speeds up over time and changes the 'zoom factor' so that the whole image is visible in the viewport at the end.
Hopefully anyone knows a libary for my problem.
I have a feeling SO doesn't like library recommendations, and actually I haven't found one, so here's some basic code to get you started.
It sets the typing speed to the old Teletype 10 chars per second and of course that can be changed, and an acceleration function can be added when you know what you want for that. Note: the txt file needs to be on the same domain to prevent CORS problems.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Typewriter print</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: Courier, monospace;
font-size: 12px;
}
</style>
</head>
<body>
<div id="container">
<input id="file" type="text" value="" placeholder="Filename" />
<button onclick="loadFile()">Click to draw the file</button>
<div id="picture"></div>
</div>
<script>
let file = '';
let reader = new XMLHttpRequest();
function loadFile() {
file = document.getElementById('file').value;
reader.open('get', file, true);
reader.onreadystatechange = draw;
reader.send(null);
}
function draw() {
if (reader.readyState == 4) {
const picture = document.getElementById('picture');
picture.innerHTML = '';
let str = reader.responseText;
let chs = str.split('');
//set as the typing speed in characters
//per second 10 is the old teletype speed
let chsPerSec = 10;
let i = 0;
function reveal() {
if (i < chs.length) {
let nextch = chs[i];
if (nextch.charCodeAt(0) == 10) {
nextch = '<br>';
} else if (nextch.charCodeAt(0) == 32) {
nextch = '<span style="color:transparent;">.</span>';
}
picture.innerHTML = picture.innerHTML + nextch;
setTimeout(reveal, Math.floor(1000 / chsPerSec));
i++;
}
}
reveal();
}
}
</script>
</body>
</html>

Adding paging controls to a full page touch swiper/slider - Hammer.js

CLICK FOR FIDDLE
Below is a fully functional full page touch slider I have created using hammer.js
You can drag, swipe or pan to navigate between pages.
The slider works as expected but I am now trying to create fallback navigation by adding two buttons so paging left and right can occur on click also.
QUESTION
How can the hammer swipe left or right be called on click? (Javascript or jQuery).
CURRENT ATTEMPT
$('#Left').on('click', function() {
HammerCarousel(document.querySelector('.Swiper'), 'Left');
});
FULL CODE
function swipe() {
var reqAnimationFrame = (function () {
return window[Hammer.prefixed(window, "requestAnimationFrame")] || function (callback) {
setTimeout(callback, 1000 / 60);
}
})();
function dirProp(direction, hProp, vProp) {
return (direction & Hammer.DIRECTION_HORIZONTAL) ? hProp : vProp
}
function HammerCarousel(container, direction) {
this.container = container;
this.direction = direction;
this.panes = Array.prototype.slice.call(this.container.children, 0);
this.containerSize = this.container[dirProp(direction, 'offsetWidth', 'offsetHeight')];
this.currentIndex = 0;
this.hammer = new Hammer.Manager(this.container);
this.hammer.add(new Hammer.Pan({ direction: this.direction, threshold: 10 }));
this.hammer.on("panstart panmove panend pancancel", Hammer.bindFn(this.onPan, this));
this.show(this.currentIndex);
}
HammerCarousel.prototype = {
show: function (showIndex, percent, animate) {
showIndex = Math.max(0, Math.min(showIndex, this.panes.length - 1));
percent = percent || 0;
var className = this.container.className;
if (animate) {
if (className.indexOf('animate') === -1) {
this.container.className += ' animate';
}
} else {
if (className.indexOf('animate') !== -1) {
this.container.className = className.replace('animate', '').trim();
}
}
var paneIndex, pos, translate;
for (paneIndex = 0; paneIndex < this.panes.length; paneIndex++) {
pos = (this.containerSize / 100) * (((paneIndex - showIndex) * 100) + percent);
translate = 'translate3d(' + pos + 'px, 0, 0)';
this.panes[paneIndex].style.transform = translate;
this.panes[paneIndex].style.mozTransform = translate;
this.panes[paneIndex].style.webkitTransform = translate;
}
this.currentIndex = showIndex;
},
onPan: function (ev) {
var delta = dirProp(this.direction, ev.deltaX, ev.deltaY),
percent = (100 / this.containerSize) * delta,
animate = false;
if (ev.type == 'panend' || ev.type == 'pancancel') {
if (Math.abs(percent) > 20 && ev.type == 'panend') {
this.currentIndex += (percent < 0) ? 1 : -1;
}
percent = 0;
animate = true;
}
this.show(this.currentIndex, percent, animate);
}
};
var outer = new HammerCarousel(document.querySelector('.Swiper'), Hammer.DIRECTION_HORIZONTAL);
};
$(swipe);
html,
body,
.Page,
.Swiper{
position:relative;
height:100%;
}
.Swiper{
background:#666;
overflow:hidden;
}
.Swiper.animate > .Page{
transition:all .3s;
-webkit-transition:all .3s;
}
.Page{
position:absolute;
top:0;
left:0;
height:100%;
width:100%;
padding:0 10px;
font:42px Arial;
color:#fff;
padding-top:10%;
text-align:center;
}
.Page:nth-child(odd) {
background:#b00;
}
.Page:nth-child(even) {
background:#58c;
}
#Left,
#Right{
position:absolute;
top:0;
height:50px;
width:50px;
background:#fff;
text-align:center;
font:16px/3em Arial;
cursor:pointer;
}
#Left{
left:0;
}
#Right{
right:0;
}
<script src="http://hammerjs.github.io/dist/hammer.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="Swiper">
<div class="Page">PAGE 1<br/>DRAG LEFT</div>
<div class="Page">PAGE 2<br/>SWIPE ME</div>
<div class="Page">PAGE 3<br/>HOLD TO PAN</div>
<div class="Page">PAGE 4<br/>FLICK TO GO BACK</div>
</div>
<div id="Left">Left</div>
<div id="Right">Right</div>
I have crafted a jQuery solution for this that should satisfy the fallback you are looking for.
Some things to consider, though. In your example as well, page re-size is not accounted for. I have not done so in this either to remain consistent and solve the immediate issue, but you will notice I am grabbing the $('.Page').width(); as a variable in this solution. I would recommend re-assigning this value if you do account for re-sizing. Also, a mix of swiping/clicking will throw this off. I assume since you indicated this will be a fallback, the user will receive one of the two experiences. If not, we'll need a way to update tracker on swipe events as well.
You'll notice var tracker = { 'R': 0 }. While naming may not be the best, 'R' will account for how many right "swipes" (navigation clicks) the user has performed in a plus/minus 1 manner
<div id="Left" direction="L">Left</div>
<div id="Right" direction="R">Right</div>
$(function() {
var width = $('.Page').width();
var pages = $('.Page').length;
var tracker = { 'R': 0 }
$('#Right, #Left').click(function() {
$(this).attr('direction') === 'R' ?
((tracker.R < (pages - 1) ? tracker.R += 1 : pages)) :
(tracker.R > 0) ? (tracker.R -= 1) : 0;
$('.Swiper').animate({ 'scrollLeft': $('.Page').width() * tracker.R }, 250)
});
});
JSFiddle Link

CSS Sprite code works in Chrome and IE but not in Firefox?

I wrote simple animation using CSS and HTML using sprites.
It works successful in chrome and IE but not firefox.
<style type="text/css">
#sprite {
width: 96px;
height: 117px;
background: url(../../images/sprite_animation_frames.png) 0px 0px;
}
</style>
</head>
<body onload="main();">
<p align="center"><h1>The Running Man</h1></p>
<script>
var position = [
[0, 0],[-100, 0],[-200, 0],[-300, 0],[-400, 0],[-500, 0],
[0,-120],[-100,-120],[-200,-120],[-300,-120],[-400,-120],[-500,-120],
[0,-240],[-100,-240],[-200,-240],[-300,-240],[-400,-240],[-500,-240],
[0,-360],[-100,-360],[-200,-360],[-300,-360],[-400,-360],[-500,-360],
[0,-480],[-100,-480],[-200,-480],[-300,-480],[-400,-480],[-500,-480]
];
var pos;
function main(){
var img = document.createElement('img')
img.id = 'sprite';
document.body.appendChild(img);
setInterval(function () {
anim(img);
}, 50);
}
var i = 0;
function anim(el) {
if (i < 30)
i++;
else
i = 0;
var x = position[i][0];
var y = position[i][1];
el.style.backgroundPositionX = x + 'px ';
el.style.backgroundPositionY = y + 'px ';
}
</script>
what could be the problem ?
Firefox does not support individual backgroundPositionX/Y properties, and IE may be complaining about the extra space. Try:
el.style.backgroundPosition = x+"px "+y+"px";
Able to solve the problem.
Just replaced div tag instead of img and it worked.
Don't know the issue.

Javascript: Memory efficient way to do this effect

I wrote the code in Javascript but any good alternative would do.
EFFECT: onmousemove over the webpage circles of random colors should create wherever the mouse moves. and they have to be added behind a mask image(circles are visible only in the transparent portion of the image which is a logo. thus creating a color paint to create logo onmousemove.
it doesn't work in jsfidde because of its memory intensiveness.
WORKING LINK: http://goo.gl/DNRxO9
I pasted the exact code you can create a new html file with the following code and IT WORKS PERFECT IN FIREFOX ONLY because of its memory intensiveness(lots of divs added in very short time so DOM becomes very very heavy).
<html>
<head>
<style type="text/css">
body{
padding:0;
margin:0;
overflow: hidden;
}
#mask{
width:100%;
height:auto;
position:absolute;
z-index:10;
}
#logo{
width:50%;
height:50%;
margin:auto;
}
.point{
width:0px;
height:0px;
background-color:#ff0000;
position:absolute;
z-index:5;
left:50px;top:50px;
border-width:50px;
border-style: solid;
border-color:red;
border-radius:50px;
opacity:1;
transition: border-width 3s ease-in-out;
}
.no-border{border-width:0px;}
</style>
<script type="text/javascript">
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.round(Math.random() * 15)];
}
return color;
}
/* OptionalCode: for removing divs after a lot are created */
Element.prototype.remove = function() {
this.parentElement.removeChild(this);
}
NodeList.prototype.remove = HTMLCollection.prototype.remove = function() {
for(var i = 0, len = this.length; i < len; i++) {
if(this[i] && this[i].parentElement) {
this[i].parentElement.removeChild(this[i]);
}
}
}
i=0;
function colors(event){
var x=event.clientX;
var y=event.clientY;
var point = document.getElementsByClassName('point');
document.body.innerHTML += "<div class='point'></div>";
point[i].style.borderColor = getRandomColor();
//point[i].className += ' no-border';
point[i].style.left = x + 'px';
point[i].style.top = y + 'px';
i++;
}
function position(){
var ht = window.getComputedStyle(document.getElementById("mask"), null).getPropertyValue("height");
var ht_num = Number(ht.slice(0,ht.length - 2));
margin_top = (Number(document.body.clientHeight) - ht_num)/2;
document.getElementById('mask').style.marginTop = margin_top + "px";
}
</script>
</head>
<body onload="position();" onmousemove="colors(event)">
<img id="mask" src="http://goo.gl/EqfJ0L">
</body>
</html>
There is one HUGE, HUGE, HUGE performance killer in your code:
document.body.innerHTML += "<div class='point'></div>";
This takes your entire document, throws it away and just inserts everything back again. This is horrible! Remember this for all times and never do this again! ;)
Keep the basic rule in mind, to never add Elements via .innerHTML!
The correct way to go is the following:
// create your new div element
var circleElement = document.createElement("div");
// add all the stuff needed
circleElement.classList.add("point");
circleElement.style.borderColor = getRandomColor();
circleElement.style.left = x + 'px';
circleElement.style.top = y + 'px';
// now append the element to the body
document.body.appendChild(circleElement);
This creates a single div and nicely inserts it as a child-element of the body.
Additionally you can decrease the number of divs drawn by introducing a threshhold:
var lastX=0,lastY=0;
function colors(event){
var x=event.clientX;
var y=event.clientY;
if (Math.abs(lastX - x) + Math.abs(lastY - y) <= 10 ) return;
/* do stuff */
lastX = x;lastY = y;
}
As a third measure you can decrease the size of the image to just hold the mask element and trigger the mousemove only on the image (because divs outside the mask are hidden anyway).
Ultimately, you could kill "old" div-elements when you have reached a certain amount.
I have not included these two last optimizations, but look at the already supersmooth example now!

How to move/slide an image from left to right

I want to slide or move a image from left to right something like in
http://rajeevkumarsingh.wix.com/pramtechnology
The read pentagonal box that moves Ok!
I tried a bit but failed to do so.
I used the code as below:
<script type="text/javascript">
<!--
var imgObj = null;
var animate ;
function init(){
imgObj = document.getElementById('myImage');
imgObj.style.position= 'absolute';
imgObj.style.top = '240px';
imgObj.style.left = '-300px';
imgObj.style.visibility='hidden';
moveRight();
}
function moveRight(){
if (parseInt(imgObj.style.left)<=10)
{
imgObj.style.left = parseInt(imgObj.style.left) + 5 + 'px';
imgObj.style.visibility='visible';
animate = setTimeout(moveRight,20); // call moveRight in 20msec
//stopanimate = setTimeout(moveRight,20);
}
else
stop();
f();
}
function stop(){
clearTimeout(animate);
}
window.onload =init;
//-->
</script>
<img id="myImage" src="xyz.gif" style="margin-left:170px;" />
There some kind of resolution problem with Firefox and IE as well. How to solve them. Also I am not able to move the things so clearly. Is this possible or not? I want it to be with JavaScript and not Flash.
var animate, left=0, imgObj=null;
function init(){
imgObj = document.getElementById('myImage');
imgObj.style.position= 'absolute';
imgObj.style.top = '240px';
imgObj.style.left = '-300px';
imgObj.style.visibility='hidden';
moveRight();
}
function moveRight(){
left = parseInt(imgObj.style.left, 10);
if (10 >= left) {
imgObj.style.left = (left + 5) + 'px';
imgObj.style.visibility='visible';
animate = setTimeout(function(){moveRight();},20); // call moveRight in 20msec
//stopanimate = setTimeout(moveRight,20);
} else {
stop();
}
//f();
}
function stop(){
clearTimeout(animate);
}
window.onload = function() {init();};
Here is an example of moving an image to the right as well as fading in from a .js file instead of your index page directly:
----------My index.html page----------
<!DOCTYPE html>
<html>
<body>
<script src="myJava.js"></script>
<script language="javascript" type="text/javascript">
//In pixels
var amountToMoveTotal = 1000;
var amountToMovePerStep = 10;
//In milliseconds
var timeToWaitBeforeNextIncrement = 20;
var amountToFadeTotal = 1.0;
var amountToFadePerStep = 0.01;
</script>
<p>This one moves right on hover</p>
<img onmouseover="moveRight(this, amountToMoveTotal, amountToMovePerStep, timeToWaitBeforeNextIncrement)" src="http://www.w3schools.com/jsref/smiley.gif" style="left:0px;top:50px;position:absolute;opacity:1.0;">
<br><br>
<p>This one fades in on hover</p>
<img onmouseover="fadeIn(this, amountToFadeTotal, amountToFadePerStep, timeToWaitBeforeNextIncrement)" src="http://www.w3schools.com/jsref/smiley.gif" style="left:0px;top:150px;position:absolute;opacity:0.1;">
</body>
</html>
----------My myJava.js code----------
var animate;
var original = null;
function moveRight(imgObj, amountToMoveTotal, amountToMovePerStep, timeToWaitBeforeNextIncrement)
{
//Copy original image location
if (original === null){
original = parseInt(imgObj.style.left);
}
//Check if the image has moved the distance requested
//If the image has not moved requested distance continue moving.
if (parseInt(imgObj.style.left) < amountToMoveTotal) {
imgObj.style.left = (parseInt(imgObj.style.left) + amountToMovePerStep) + 'px';
animate = setTimeout(function(){moveRight(imgObj, amountToMoveTotal, amountToMovePerStep, timeToWaitBeforeNextIncrement);},timeToWaitBeforeNextIncrement);
}else {
imgObj.style.left = original;
original = null;
clearTimeout(animate);
}
}
function fadeIn(imgObj, amountToFadeTotal, amountToFadePerStep, timeToWaitBeforeNextIncrement)
{
//Copy original opacity
if (original === null){
original = parseFloat(imgObj.style.opacity);
}
//Check if the image has faded the amount requested
//If the image has not faded requested amount continue fading.
if (parseFloat(imgObj.style.opacity) < amountToFadeTotal) {
imgObj.style.opacity = (parseFloat(imgObj.style.opacity) + amountToFadePerStep);
animate = setTimeout(function(){fadeIn(imgObj, amountToFadeTotal, amountToFadePerStep, timeToWaitBeforeNextIncrement);},timeToWaitBeforeNextIncrement);
}else {
imgObj.style.opacity = original;
original = null;
clearTimeout(animate);
}
}
Use the jQuery library, is really easy to do what you need
http://api.jquery.com/animate/
Follow sample code of page : http://api.jquery.com/stop/
<!DOCTYPE html>
<html>
<head>
<style>div {
position: absolute;
background-color: #abc;
left: 0px;
top:30px;
width: 60px;
height: 60px;
margin: 5px;
}
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<button id="go">Go</button>
<button id="stop">STOP!</button>
<button id="back">Back</button>
<div class="block"></div>
<script>
/* Start animation */
$("#go").click(function(){
$(".block").animate({left: '+=100px'}, 2000);
});
/* Stop animation when button is clicked */
$("#stop").click(function(){
$(".block").stop();
});
/* Start animation in the opposite direction */
$("#back").click(function(){
$(".block").animate({left: '-=100px'}, 2000);
});
</script>
</body>
</html>

Categories

Resources