javascript change image slowly with fade using timer and opacity - javascript

i am looking for some help with this script i have been working on. here is my file fade.js
the problem is with the changing, it is messed up. please help me find the problem and solution for this, thanks.
JS-file
//image fade script
var opacity = 0;
function changeimg(currentimage){
rnumb = Math.floor(Math.random()*2);
var newimage = "./images/" + rnumb + ".jpg";
if (newimage !== currentimage)
{
document.getElementById("fadeImg").src= newimage;
}
}
function fadein()
{
var fadeImg = document.getElementById('fadeImg');
var browserName=navigator.appName;
if(browserName=="Microsoft Internet Explorer")
{
browserOpacity = opacity / 10;
fadeImg.filters.alpha.opacity = browserOpacity;
}
else
{
browserOpacity = opacity / 1000;
fadeImg.style.opacity = browserOpacity;
}
if(opacity < 1000)
{
initiate();
}
else if(opacity == 1000)
{
changeimg(document.getElementById("fadeImg").src);
opacity = 0;
}
}
function initiate()
{
opacity++;
setInterval("fadein()", 500);
}
index.html
<script type="text/javascript" src="fade.js"></script>
<body onload="initiate()">
<img id="fadeImg" src="images/1.jpg" style="opacity:0.0; filter:alpha(opacity=0)"/>
</body>
JS-fiddle
Here is a Fiddle of the code as well: http://jsfiddle.net/epqKr/2/ (Notice that the code, as it is in the fiddle, may make your browser freeze after a while.

I think you should use a cross-browser library to accomplish things like this.
Microsoft Internet Explorer, especially in versions < 9, is most likely to not behave
as you would expect it does, particularly when you try to use functions which makes use of opacity, alpha-filter and timing. You could try to use jQuery, or Prototype, or MooTools and such frameworks. They all make what you're looking for in simple, secure, better way.

Don't call initiate() from within the fadeIn() function, instead just increment your opacity control variable (i.e, opacity += 1;).
You will probably want to save your setInterval return value to kill the callbacks when you have finished your animation.
You also probably will want to increase the animation speed by lowering the interval.
animId = setInterval("fadeIn()", 5);

i am working on this still, heres what i have now: it doesnt work whatsoever but it looks better.
html
<html>
<head>
<script type="text/javascript" src="fade1.js"></script>
</head>
<body onload="fadetimer()">
<img id="fadeImg" src="1.jpg" style="opacity:0.0; filter:alpha(opacity=0)"/>
</body>
</body>
</html>
script
//image fade script
var opacity = 0;
function changeimg(currentimage){
rnumb = Math.floor(Math.random()*2);
var newimage = rnumb + ".jpg";
if (newimage !== currentimage)
{
document.getElementById("fade").src= newimage;
}
}
function fadein()
{
var fade = document.getElementById('fade');
if(fade.filters.alpha.opacity >= 100 || fade.style.opacity >= 1.0)
{
changeimg(fade.src);
fade.filters.alpha.opacity = 0;
fade.style.opacity = 0;
}
else
{
fade.filters.alpha.opacity += 10;
fade.style.opacity += 0.1;
}
}
function fadetimer()
{
setInterval("fadein()", 500);
}

Related

Scrollbar behaviour on Firefox/Chrome - function to hide it but being able to scroll up?

I'm working for an artistic project and I'm struggling with a little thing I may have solved for Chrome but not for Firefox. I have a page where a text will be written by an A.I through a MySQL database. Quickly, the text will be out of its container so we managed to hide the scrollbar and follow the writing process without allowing the viewer to scroll up. Now I'm trying to allow the viewer to scroll up when the process is paused or done. You can see the test page here : http://82.223.18.239/writing7.php
I tried a few ways :
Using overflow:hidden all the time. This isn't working, the viewer can't scrollup when the writing process is paused or done.
switching from overflow:hidden to overflow:scroll when the writing is paused or done. In this case the window is forced back on the top of the page. This isn't good. I would like the view to stay at the bottom, where the writing is paused.
switching from overflow:hidden to overflow:scroll when the writing is paused or done. In this case the scrollbar is weirdly positioned and I didn't find any way to put it back on the right. It's glued to the myTables div, whatever I'm trying. When I'm trying to set it up on <body> this isn't working at all.
switching from overflow:hidden to overflow:scroll AND hidding the scrollbar. It maybe a bit messy but it works well for Chrome, by using ::-webkit-scrollbar {display: none;} but it doesn't work at all for Firefox.
To summarize, I would like the view to follow the writing process, like it does now, and I would like the user to be able to scroll up only when it's paused or done, allowing him/her to read the full text but I didn't find anyway to make it work. Could you help me a bit ?
Actually, I'm trying to change the overflow value of a #parent / #child div through this part of the showtext function, but it doesn't work either.
else {
get_data(skip);
$('#body').css('overflow', 'hidden')
$('#myTable').css('overflow-y', 'scroll').css('overflow-x', 'hidden')
}
Here's the actual full code :
<head>
<div id="header"></div>
<div id="body"></div>
<div id="footer"></div>
<div id="myTable"> <div>
<script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<style type="text/css">
#myTable{
width:"90%";
height:"100%";
min-width:250px;
white-space: pre-wrap;
word-wrap:break-word;
position:absolute;
border:solid 0px;
top:-500px;
left:320px;
right:320px;
bottom:0px;
font-size:103px;
font-family:"Times New Roman", Times, serif;
text-align:left
}
#body{
height:"100%";
min-width:250px;
}
#footer{
height:"0px";
}
::-webkit-scrollbar {display: none;}
</style>
</head>
<body>
<myTable>
<script type="text/javascript">
var skip = 0;
function get_data(index) {
$.ajax({
url : 'http://82.223.18.239/getData.php',
type : 'POST',
data: ({"skip":skip}),
success : function(data) {
if(data && data.trim()!='') {
skip = skip+1;
showText("#myTable", data, 0, 2);
}
else {
setTimeout(function () { get_data(skip); }, 30000);
}
},
error : function(request,error)
{
alert("Request error : "+JSON.stringify(request));
}
});
}
function showText(target, message, index, interval) {
if (index < message.length) {
$(target).append(message[index++]);
setTimeout(function () { showText(target, message, index, interval); }, interval);
$('#myTable').css('overflow', 'hidden').bind('DOMNodeInserted', function () {
this.scrollTop = this.scrollHeight;
});
}
else {
get_data(skip);
$('#body').css('overflow', 'hidden')
$('#myTable').css('overflow-y', 'scroll').css('overflow-x', 'hidden')
}
}
//var period = 10000; //NOTE: period is passed in milliseconds
get_data(skip);
//setInterval(page_refresh, period);
</script>
</myTable>
</body>
<footer>
<SCRIPT LANGUAGE="JavaScript">
var message = new Array();
message[0] = ""
var reps = 2;
var speed = 666;
var p = message.length;
var T = "";
var C = 0;
var mC = 0;
var s = 0;
var sT = null;
if (reps < 1) reps = 1;
function doIt() {
T = message[mC];
A();
}
function A() {
s++;
if (s > 8) { s = 1;}
if (s == 1) { document.title = '✊🏻✊✊🏼✊✊🏽✊✊🏾✊✊🏿✊✊🏻✊✊🏼✊✊✊🏻✊✊🏼✊✊🏽✊✊🏾'+T+'✊🏻✊✊🏼✊✊🏽✊✊🏾✊✊🏿✊✊🏻✊✊🏼✊✊🏽✊✊🏾✊✊'; }
if (s == 2) { document.title = '☠️☠️☠️☠️☠️☠️☠️☠️☠️☠️☠️☠️☠️☠️☠️☠️☠'+T+'☠️☠️☠️☠️☠️☠️☠️☠️☠️☠️☠️☠️☠️☠️☠️☠️☠️☠️'; }
if (s == 3) { document.title = '🌍🌎🌍🌎🌍🌎🌏🌍🌎🌍🌎🌍🌎🌏🌍🌎🌍🌎🌍🌎🌏'+T+'✊🏻✊✊🏼✊✊🏽✊✊🏾✊✊🏿✊✊🏻✊✊🏼✊✊'; }
if (s == 4) { document.title = '✊🏻✊✊🏼✊✊🏽✊✊🏾✊✊🏿✊✊🏻✊✊🏼✊✊🏽✊✊🏾✊✊'+T+'β›”β›”β›”β›”β›”β›”β›”β›”β›”β›”β›”β›”β›”β›”β›”β›”β›”β›”β›”β›”'; }
if (s == 5) { document.title = 'πŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”Œ'+T+'πŸ› πŸ› πŸ› πŸ› πŸ› πŸ› πŸ› πŸ› πŸ› πŸ› πŸ› πŸ› πŸ› πŸ› πŸ› πŸ› πŸ› πŸ› πŸ› πŸ› '; }
if (s == 6) { document.title = 'πŸ’£πŸ’£πŸ’£πŸ’£πŸ’£πŸ’£πŸ’£πŸ’£πŸ’£πŸ’£πŸ’£πŸ’£πŸ’£πŸ’£πŸ’£πŸ’£πŸ’£πŸ’£πŸ’£πŸ’£'+T+'πŸ––πŸ––πŸΏπŸ––πŸ––πŸΌπŸ––πŸΎπŸ––πŸΌπŸ––πŸΏπŸ––πŸ––πŸΌπŸ––πŸΎπŸ––πŸ––πŸΏπŸ––πŸ––πŸΌπŸ––πŸΎπŸ––πŸΌ'; }
if (s == 7) { document.title = 'πŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”Œ'+T+'πŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”Œ'; }
if (s == 8) { document.title = '✊🏻✊✊🏼✊✊🏽✊✊🏾✊✊🏿✊✊🏻✊✊🏼✊✊🏽✊✊🏾✊✊🏿'+T+'⏳⏳⏳⏳⏳⏳⏳⏳⏳⏳⏳⏳⏳⏳⏳⏳⏳⏳⏳⏳⏳'; }if (C < (8 * reps)) {
sT = setTimeout("A()", speed);
C++;
}
else {
C = 0;
s = 0;
mC++;
if(mC > p - 1) mC = 0;
sT = null;
doIt();
}
}
doIt();
(function() {
var template = 'βœŠβ˜”β˜β˜β˜β˜ β›”β˜β˜β˜β³β˜”βš β˜β˜β›”β³β˜ β˜β˜β˜β˜β˜πŸ’£βœŠπŸΎ'.split(''),
len = template.length,
chars, string, i, j, k,
pushOrHash = typeof window.history.pushState === 'function',
increase = function(n) {
return n < len - 1 ? n + 1 : 0;
},
update = function() {
chars = [];
j = k;
for (i=0; i<len; i++) {
j = increase(j);
chars[i] = template[j];
}
string = ['/', chars.join(''), '/'].join('');
k = increase(k);
if (pushOrHash) {
window.history.pushState(null, null, string);
} else {
window.document.location.hash = string;
}
setTimeout(update, 1000);
};
update();
})();
</script>
</script>
<script type="text/javascript">
function pageLoad()
{
alert('The image of external things possesses for us the ambiguous dimension that in external nature everything can be considered to be connected, but also as separated. The uninterrupted transformations of materials as well as energies brings everything into relationship with everything else and make one cosmos out of all the individual elements. On the other hand, however, the objects remain banished in the merciless separation of space; no particle of matter can share its space with another and a real unity of the diverse does not exist in spatial terms. And, by virtue of this equal demand on self-excluding concepts, natural existence seems to resist any application of them at all. Only to humanity, in contrast to nature, has the right to connect and separate been granted, and in the distinctive manner that one of these activities is always the presupposition of the other. By choosing two items from the undisturbed store of natural things in order to designate them as -separate-, we have already related them to one another in our consciousness, we have emphasized these two together against whatever lies between them. And conversely, we can only sense those things to be related which we have previously somehow isolated from one another; things must first be separated from one another in order to be together. Practically as well as logically, it would be meaningless to connect that which was not separated, and indeed that which also remains separated in some sense. The formula according to which both types of activity come together in human undertakings, whether the connectedness or the separation is felt to be what was naturally ordained and the respective alternative is felt to be our task, is something which can guide all our activity. In the immediate as well as the symbolic sense, in the physical as well as the intellectual sense, we are at any moment those who separate the connected or connect the separate. Georg Simmel from -Bridges and Doors- 1909ΜΏ');
}
pageLoad();
</script>
</footer>
You used to be able to use overflow: -moz-scrollbars-none; but it is depreciated in recent versions of firefox.
And attempting to change overflow-x or overflow-y has also been depreciated.
I recommend setting your right margin (or whichever side the scrollbar is on) to a value equal to the width of the scrollbar, only negative. Then when you want to show the scrollbar, all you have to do is adjust the margin.
Note that depending on your layout you may have to also set the other margins (top, bottom and left) in order for your content to look consistent and have appropriate spacing.
I finally find a way to do exactly what I wanted.
For Google Chrome and webkit browsers, you simply have to do overflow:hidden and hide the scrollbar with ::-webkit-scrollbar {display: none;}
For other browsers, you'll have to set -ms-overflow-style:none and use
var textareaWidth = document.getElementById("yourdiv").scrollWidth;
document.getElementById("yourdiv").style.width = textareaWidth + "px";
More specifically, for me it worked by rewriting the showtext function like this :
function showText(target, message, index, interval) {
if (index < message.length) {
$(target).append(message[index++]);
setTimeout(function () { showText(target, message, index, interval); }, interval);
$('#myTable').css('overflow', 'hidden').bind('DOMNodeInserted', function () {
this.scrollTop = this.scrollHeight;
});
}
else if (navigator.userAgent.toLowerCase().indexOf('firefox') > -1){
get_data(skip);
$('#myTable').css('overflow', 'hidden')
document.getElementById("myTable").style.width = textareaWidth + "px";
}
else if (/MSIE 9/i.test(navigator.userAgent) || /rv:11.0/i.test(navigator.userAgent)){
get_data(skip);
$('#myTable').css('overflow', 'hidden').css('-ms-overflow-style', 'none')
document.getElementById("myTable").style.width = textareaWidth + "px";
}
else if (/MSIE 10/i.test(navigator.userAgent)){
get_data(skip);
$('#myTable').css('overflow', 'hidden').css('-ms-overflow-style', 'none')
document.getElementById("myTable").style.width = textareaWidth + "px";
}
else if (/Edge\/\d./i.test(navigator.userAgent)){
get_data(skip);
$('#myTable').css('overflow', 'hidden').css('-ms-overflow-style', 'none')
document.getElementById("myTable").style.width = textareaWidth + "px";
}
else {
get_data(skip);
$('#myTable').css('overflow', 'scroll')
}
}

Render HTML after each iteration in loop

I am trying to slowly increase the font size of text on a web page. The code I have in place does work, however the new HTML/CSS does not render after each iteration of the loop and will just display the 100px size text when it's all done. To make the text look like it's slowly zooming in I need to do that. The javascript is below as it is being used from a separate file. Here's what I have...
<p class="game-title" style="font-size:50px">Test</p>
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds) {
break;
}
}
}
function increaseSize() {
$('.game-title').css('font-size', parseInt($('.game-title').css('font-size')) + 1 + "px");
}
while (parseInt($('#text').css('font-size')) <= 100){
sleep(1000);
increaseSize();
}
Using CSS (sample http://jsfiddle.net/X3crE/2/):
<p class="game-title">Test</p>
<style>
.game-title { font-size:50px; transition: 2s; }
.game-title.large { font-size: 100px; }
</style>
$('.game-title').addClass('large');
Using jQuery (sample http://jsfiddle.net/X3crE/):
$('.game-title').animate({'font-size':'100px'},2000);
You need to do in asynchronously. Demo.
function increaseSize() {
var title = $('.game-title'),
size = parseInt(title.css('font-size'))
title.css('font-size', '+=1');
if(size < 100) {
setTimeout(increaseSize, 1000);
}
}
And plz never block main UI thread.
That is because you are blocking the browser from rendering in your sleep method. Browsers are single threaded, except your are using webworkers and this single thread is also responsible for rendering. You can just see the result, because your are blocking the browser from rendering with your sleep method.
Try to create something like that:
var size = 10, big = 20, step = 1;
function setFontSize(s) {
/*code to resize*/
}
function increase () {
if (size < big) {
setFontSize(size);
size += step;
window.setTimeout(increase, 1000);
}
}
increase();

Making background fade in using Javascript

Hello below is my JS code for a changing background image every 30 seconds. I have this example code too from research, can somebody please please please show me how to integrate the example code into my JS, so the changing image fades in as I simply have no clue where to start and feel completely lost.
My JS
<script>
bgArr = ['images/bg1.jpg', 'images/bg2.jpg', 'images/bg3.jpg'];
bgCur = 0;
backgroundSwitch = function()
{
if (bgCur == bgArr.length) bgCur = 0;
document.body.style.backgroundImage = 'url('+ bgArr[bgCur++]+ ')';
}
window.setInterval(backgroundSwitch, 30000); // Switch every 30 seconds.
</script>
Example JS that I want to integrate
var img = document.getElementById("fade");
var fadeLength = 5500;
var opacity = 0;
var startTime = Date.now();
requestAnimationFrame(function me() {
// It's faded in, stop animating!
if (opacity >= 1) {
return;
}
opacity = (Date.now() - startTime) / fadeLength;
img.textContent = opacity;
img.style.opacity = opacity;
requestAnimationFrame(me);
});
Also is there a way to fit the background to the browser window within the javascript without using css?
Thank you and somebody please help!
One solution here is to use CSS transitions. No JS transition needed.
transition: background-image 6s;
Example

setTimeout issue

I'm trying to create a jquery fadeto type of effect in Javascript, but am having an issue with my setTimeout command.
Here is the code:
function textfade(y) {
var x = document.getElementById("test");
var y;
if (y == undefined) {
y = 1.0;
}
x.style.opacity = y;
y -=0.1;
setTimeout(function(){ textfade(y); }, 50);
}
The problem is x.style.opacity = y.
Without that, the timeout runs fine. With it, however, it runs through the function one time and then dies. While I feel like it's a simple error, I am out of ideas for fixing it.
Any advice would be greatly appreciated.
Thank you in advance.
You're re-declaring y each time textfade() is executed, effectively destroying / resetting the passed parameter.
Remove:
var y;
Ensure that you are running it after test element is already available. Here it works fine: http://jsfiddle.net/3yDMP/ . And here: http://jsfiddle.net/3yDMP/3/ - no , because function is called in head, not in onload (like in first fiddle), when dom is not ready yet and is not available.
So, in your could be
<head>
<script>
function textfade() {...}
</script>
</head>
<body onload="textfade()">
<div id="test"> ... </div>
IMHO this would be better with the setTimeout calling an internal closure where the current opacity level is maintained outside of the fade function itself, so you don't have to pass it around.
function textfade(el) {
if (typeof el === "string") {
el = document.getElementById(el);
}
var opacity = 1.0;
(function fade() {
el.style.opacity = opacity;
opacity -= 0.1;
if (opacity > 0) {
setTimeout(fade, 50);
}
})();
}
demo at http://jsfiddle.net/alnitak/TQHYj/

Showing/hiding <div> using javascript

For example I have a function called showcontainer. When I click on a button activating it, I want a certain div element, in this case <div id="container">, to fade in. And when I click it again, fade out.
How do I achieve this?
Note: I am not accustomed with jQuery.
So you got a bunch of jQuery answers. That's fine, I tend to use jQuery for this kind of stuff too. But doing that in plain JavaScript is not hard, it's just a lot more verbose:
var container = document.getElementById('container');
var btn = document.getElementById('showcontainer');
btn.onclick = function() {
// Fade out
if(container.style.display != 'none') {
var fade = setInterval(function(){
var opacity = parseFloat(container.style.opacity);
opacity = isNaN(opacity) ? 100 : parseInt(opacity * 100, 10);
opacity -= 5;
container.style.opacity = opacity/100;
if(opacity <= 0) {
clearInterval(fade);
container.style.opacity = 0;
container.style.display = 'none';
}
}, 50);
// Fade in
} else {
container.style.display = 'block';
container.style.opacity = 0;
var fade = setInterval(function(){
var opacity = parseFloat(container.style.opacity);
opacity = isNaN(opacity) ? 100 : parseInt(opacity * 100, 10);
opacity += 5;
container.style.opacity = opacity/100;
if(opacity >= 100) {
clearInterval(fade);
container.style.opacity = 1;
}
}, 50);
}
};
Check the working demo.
Provided you're not opposed to using jQuery per se, you can achieve this easily:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#showcontainer').click(function() {
$('#container').fadeToggle();
});
});
</script>
...
<div id="container">
...
</div>
...
<input type="button" id="showcontainer" value="Show/hide"/>
...
Note the missing http: in the beginning of the source of jQuery. With this trick the browser will automatically use http: or https: based on whether the original page is secure.
The piece of code after including jQuery assigns the handler to the button.
Best thing you could do is start now and get accustomed to jQuery.
The page http://api.jquery.com/fadeIn/ has all the example code that could be written here. Basically you want to have the call to fadeIn in your showcontainer function.
function showcontainer() {
$('#container').fadeIn();
}
You can have a look at jQuery UI Toggle.
The documentation turns the use of the library very simple, and they have many code examples.
You'd be as well off learning jQuery as it makes it a lot easier to do things!
From the sounds of it, you could have the container div already in the HTML but with a style of "display:none;", and then simply show it in your click event using (jQuery):
$('#container').fadeIn('slow', function() {
//Any additional logic after it's visible can go here
});

Categories

Resources