Currently I have a homepage for my website with a slideshow (4 pictures) as my background. The transition between images isn't very smooth and jumps from photo to photo. How can I create smoother transitions, is it possible to fade in and fade out?
All help greatly appreciated, thanks
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function(){
var header = $('body');
var backgrounds = new Array(
'url(http://urs2009.net/wp-content/uploads/2011/11/lights-of-city.jpg)'
, 'url(http://www.wallpaiper.com/wp-content/uploads/2014/06/amazing-wallpaper-hd-8.jpg)'
, 'url(http://hdwallpaperd.com/wp-content/uploads/2014/12/background-wallpaper-hd-1.jpg)'
, 'url(http://www.mrwallpaper.com/wallpapers/rocky-beach-hd.jpg)'
);
var current = 0;
function nextBackground() {
current++;
current = current % backgrounds.length;
header.css('background-image', backgrounds[current]);
}
setInterval(nextBackground, 5000);
header.css('background-image', backgrounds[0]);
});
</script>
Change your JS to this to make it more efficient. It would be better that you create a div that covers the entire body if you want the fade animations.:
HTML:
<body>
<div id="div1"></div>
</body>
CSS:
#div1
{
position:absolute;
top:0;
left:0;
bottom:0;
right: 0;
}
Javascript:
$(document).ready(function(){
var backgrounds = new Array(
'url(http://urs2009.net/wp-content/uploads/2011/11/lights-of-city.jpg)'
, 'url(http://www.wallpaiper.com/wp-content/uploads/2014/06/amazing-wallpaper-hd-8.jpg)'
, 'url(http://hdwallpaperd.com/wp-content/uploads/2014/12/background-wallpaper-hd-1.jpg)'
, 'url(http://www.mrwallpaper.com/wallpapers/rocky-beach-hd.jpg)'
);
var current = 0;
function nextBackground() {
if(current<backgrounds.length)
current++;
else
current=0;
$('#div1').fadeOut(function() {
$('#div1').css({background : backgrounds[current]) });
$('#div1').fadeIn(5000);
}, 5000);
}
setInterval(nextBackground, 5000);
});
It's difficult to fade background images as they have no opacity state. You can either have a -z-index div the same size as the body, and fade images in it behind the rest of your content, or you can float a mask over your background and dip to black (or another color) while you switch images. This is a simple method of doing the latter:
HTML:
<div id = "mask"></div>
CSS
#mask {
width:100%;
height:100%;
background:#000000;
top:0;
left:0;
position:absolute;
display:none;
}
jquery
$(document).ready(function(){
var header = $('body');
var backgrounds = new Array(
'url(http://urs2009.net/wp-content/uploads/2011/11/lights-of-city.jpg)'
, 'url(http://www.wallpaiper.com/wp-content/uploads/2014/06/amazing-wallpaper-hd-8.jpg)'
, 'url(http://hdwallpaperd.com/wp-content/uploads/2014/12/background-wallpaper-hd-1.jpg)'
, 'url(http://www.mrwallpaper.com/wallpapers/rocky-beach-hd.jpg)'
);
var current = 0;
function nextBackground() {
$('#mask').fadeTo(1000, 0.9, function() {
current++;
current = current % backgrounds.length;
header.css('background-image', backgrounds[current]);
})
$('#mask').fadeTo(500, 0);
}
setInterval(nextBackground, 5000);
header.css('background-image', backgrounds[0]);
});
You can obviously play with the color, timers and opacity to get the effect you want.
FIDDLE
Related
var images = ["https://dummyimage.com/600x400/c4c4c4/0011ff.jpg&text=Image+1", "https://dummyimage.com/600x400/c4c4c4/ff0000.jpg&text=Image+2", "https://dummyimage.com/600x400/c4c4c4/fffb00.jpg&text=Image+3"];
$(function () {
var i = 0;
$("#dvImage").css("background-image", "url(" + images[i] + ")");
setInterval(function () {
i++;
if (i == images.length) {
i = 0;
}
$("#dvImage").fadeOut("slow", function () {
$(this).css("background-image", "url(" + images[i] + ")");
$(this).fadeIn("slow");
});
}, 2000);
});
p {padding: 75px 15px 15px 15px;text-align: center;}
#dvImage {background-size:cover;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="dvImage" style="width: 600px;height: 400px;">
<div id="text">
<p>How do I get this text to stop fading?</p>
</div>
</div>
I'm trying to create a background image rotator, that changes images and fades between each image. I've almost got it, but on the site that I'm using it, has a nested image and text, which is also fading. I only want it to fade the background images and not any of the nested div's.
I created an example here with a nested div (and paragraph tag with text).
https://jsfiddle.net/bobthegoat2001/3hrgua82/6/
Does anyone know how I could fix this? Any help would be great. Thanks!
<p style="display:none">I guess Stack Overflow wanted some code, so I just put some random here. The jsfiddle will make more since.</p>
You can use position absolute and then set z-index to -1 but you need to move nested div's out of your div #dvImage
var images = ["https://dummyimage.com/600x400/c4c4c4/0011ff.jpg&text=Image+1", "https://dummyimage.com/600x400/c4c4c4/ff0000.jpg&text=Image+2", "https://dummyimage.com/600x400/c4c4c4/fffb00.jpg&text=Image+3"];
$(function () {
var i = 0;
$("#dvImage").css("background-image", "url(" + images[i] + ")");
setInterval(function () {
i++;
if (i == images.length) {
i = 0;
}
$("#dvImage").fadeOut("slow", function () {
$(this).css("background-image", "url(" + images[i] + ")");
$(this).fadeIn("slow");
});
}, 2000);
});
p {padding: 75px 15px 15px 15px;text-align: center;}
#dvImage {position:absolute; z-index:-1;width:600px; height:400px; background-size:cover;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="dvImage"></div>
<div id="text">
<p>How do I get this text to stop fading?</p>
</div>
I'm very new to programming and am trying to make a project for class using html, canvas, and a css file. The concept is that there should be a title screen that appears in the canvas element that once you click will disappear and reveal a room where there are elements that you can hover your mouse over and get information.
I have the html, canvas, and css up to how I want it but whenever I try to put something in the canvas element it doesn't show up. Like, for the title screen I want to draw a colored box and put some text in it and then have it click away to reveal an image underneath. I used a drawCanvas but it will only show up if I put a gameLoop at the end. But when I try to add text, it disappears. Again, I'm really new to this and I'm sorry for my wall of text but any advice or suggestions would be really helpful. Here's my html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title Page</title>
<link rel="stylesheet" type="text/css" href="css.css"/>
<script src="js/modernizr.js"></script>
<script>
window.addEventListener("load",eventWindowLoaded, false);
function eventWindowLoaded() {
canvasApp();
}
function canvasSupport() {
return Modernizr.canvas;
}
function canvasApp() {
if (!canvasSupport()) {
return;
}
var theCanvas = document.getElementById("canvasOne");
var context = theCanvas.getContext("2d");
var width=1000;
var height=450;
function drawCanvas(){
context.fillStyle="teal";
context.fillRect(0,0,width,height);
setColor();
drawLines();
}
function gameLoop(){
requestAnimationFrame(gameLoop);
drawCanvas();
}
gameLoop();
}
</script>
</head>
<body>
<audio loop="loop" autoplay="autoplay" controls="controls">
<source src="themesong.mp3" type="audio/mpeg">
Your browser does not support the audio content.
</audio>
<!-- Canvas -->
<div id="canvas-container">
<canvas id="canvasOne" width="1000" height="450">
Your browser does not support canvas.
</canvas>
</div>
<!-- ^ End Canvas -->
</body>
</html>
And here's my CSS:
#canvasOne {
background-color: #cccccc;
border: 10px solid rgba(136, 128, 172, 0.9);
margin-left: 210px;
margin-right: auto;
margin-top: 130px;
#body {
background-image: url("mansion.jpg");
background-repeat: no-repeat;
}
Honestly, if someone could just help me put an image in the canvas and make it so that certain areas where the mouse hovers over a text box would appear, would be awesome. The idea is that it's a game where you "look" around the room with your mouse for clues. And once again, I'm very new to this so sorry if this is formatted weird or my question is too ridiculously long.
I'm not sure what exactly you want but i fixed the problem where the image is not coming up on the canvas.
The problem is that on your CSS you are coloring the background then you are also putting the image on it causing it to overlap.
Here is the CSS code that I have changed:
#canvasOne {
background-image: url("mansion.jpg");
background-repeat: no-repeat;
border: 10px solid rgba(136, 128, 172, 0.9);
margin-left: 210px;
margin-right: auto;
margin-top: 130px;
}
I dont know how to do the hover part but you should look into this
This is your main problem:
window.addEventListener("load",eventWindowLoaded, false);
The reason I say that is because you are calling the evenWindowLoaded function once -- when the page initially loads. Since this is the case, whatever state the drawLines() and other functions are in when the page loads for the first time, that will be draw on the canvas.
Instead you should try to use this:
var timer = setInterval(function() { eventWindowLoaded(); }, 100);
and then clear the canvas and re-draw it.
(this is for the hover effect)
that way, you can do calculate if the mouse's cursor is above a particular space on the canvas and then do whatever functions if it is... this isn't 100% going to work, but its a general idea of what you could do:
var mousePos;
var timer = setInterval(function() { eventWindowLoaded(); }, 100);
function eventWindowLoaded() {
context.clearRect(0,0,width,height);
for (var i=0; i<images.count; ++i) {
var img = images[i];
if (Math.Abs(mousePos.x - img.Pos().x)) <= img.width) {
if (Math.Abs(mousePos.y - img.Pos().y)) <= img.height) {
do_hover_event();
}
}
}
}
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
canvas.addEventListener('mousemove', function(evt) {
mousePos = getMousePos(canvas, evt);
}
Thats one thing -- here's another:
You are leaving the scope of the variable definition for the canvas/context var's, try this method for the canvas/context -- using 3 diffeerent separate functions and defining the width, height, theCanvas, and context all in the global scope
var width=1000;
var height=450;
var theCanvas = document.getElementById("canvasOne");
var context = theCanvas.getContext("2d");
function canvasApp() {
if (!canvasSupport()) {
return;
}
gameLoop();
}
function drawCanvas(){
context.fillStyle="teal";
context.fillRect(0,0,width,height);
setColor();
drawLines();
}
function gameLoop(){
requestAnimationFrame(gameLoop);
drawCanvas();
}
I have a huge HTML5 Canvas, and I want it to work like google maps: the user can drag it and see only a small part of it (the screen's size) all the time. it renders only the part you can see on the screen.
how can I do it? do you have an idea?
2 simple steps:
place the canvas inside a div container with overflow:hidden
use any method to make your canvas draggable (I will use jQuery UI)
To follow my method you need to go to the jQuery UI website and download any version of the jQuery UI (you can create a custom version only consisting of the UI Core and Draggable Interaction for this example.)
Unpack the .zip file and move the 'js' folder to your page directory.
Inlcude the .js files contained in the folder into your page.
Place the following code between your <head></head>-tags to get your canvas draggable:
<script type="text/javacript">
$(function() {
$("#CanvasID").draggable();
});
</script>
Here's an example:
<!DOCTYPE>
<html>
<head>
<title>canvas test</title>
<script type="text/javascript" src="js/jquery-1.5.1.min.js"></script> <!-- include the jQuery framework -->
<script type="text/javascript" src="js/jquery-ui-1.8.11.custom.min.js"></script> <!-- include JQuery UI -->
<style type="text/css">
#box{
width: 400px;
height: 400px;
border:5px solid black;
overflow:hidden;
position:relative;
} /* Just some basic styling for demonstration purpose */
</style>
<script type="text/javascript">
window.onload = function() {
var drawingCanvas = document.getElementById('myDrawing');
// Check the element is in the DOM and the browser supports canvas
if(drawingCanvas.getContext) {
// Initaliase a 2-dimensional drawing context
var context = drawingCanvas.getContext('2d');
context.strokeStyle = "#000000";
context.fillStyle = "#FFFF00";
context.beginPath();
context.arc(200,200,200,0,Math.PI*2,true);
context.closePath();
context.stroke();
context.fill();
}
// just a simple canvas
$(function() {
$( "#myDrawing" ).draggable();
});
// make the canvas draggable
}
</script>
</head>
<body>
<div id="box">
<canvas id="myDrawing" width="800" height="800">
<p>Your browser doesn't support canvas.</p>
</canvas>
</div>
</body>
</html>
Hope this get's you going.
note: This is just a basic example. This will still need some editing. For example the user can drag the canvas totally out of the viewport (perhaps constraining the Canvas to the div may do the trick?). But this should be a good starting point.
I would use two canvases. Keep your huge source canvas hidden and copy portions of it to a second smaller visible canvas. Here's my quickly hacked-up proof of concept:
<!DOCTYPE HTML>
<html>
<head>
<title>canvas scroll</title>
<style type="text/css">
body {
margin: 0;
padding: 0;
overflow: hidden;
}
#source {
display: none;
}
#coords{
position: absolute;
top: 10px;
left: 10px;
z-index: 2;
}
#coords p{
background: #fff;
}
</style>
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
var $window;
var img;
var $source; var source; var sourceContext;
var $target; var target; var targetContext;
var scroll = {
x : 0,
y : 0
};
var scrollMax;
function init() {
// Get DOM elements
$window = $(window);
$source = $('canvas#source');
source = $source[0];
sourceContext = source.getContext("2d");
$target = $('canvas#target');
target = $target[0];
targetContext = target.getContext("2d");
// Draw something in source canvas
sourceContext.rect(0, 0, source.width, source.height);
var grd = sourceContext.createLinearGradient(0, 0, source.width, source.height);
grd.addColorStop(0, '#800080');
grd.addColorStop(0.125, '#4B0082');
grd.addColorStop(0.25, '#0000FF');
grd.addColorStop(0.325, '#008000');
grd.addColorStop(0.5, '#FFFF00');
grd.addColorStop(0.625, '#FFA500');
grd.addColorStop(0.75, '#FF0000');
grd.addColorStop(0.825, '#800080');
sourceContext.fillStyle = grd;
sourceContext.fill();
/*
* Setup drag listening for target canvas to scroll over source canvas
*/
function onDragging(event){
var delta = {
left : (event.clientX - event.data.lastCoord.left),
top : (event.clientY - event.data.lastCoord.top)
};
var dx = scroll.x - delta.left;
if (dx < 0) {
scroll.x = 0;
} else if (dx > scrollMax.x) {
scroll.x = scrollMax.x;
} else {
scroll.x = dx;
}
var dy = scroll.y - delta.top;
if (dy < 0) {
scroll.y = 0;
} else if (dy > scrollMax.y) {
scroll.y = scrollMax.y;
} else {
scroll.y = dy;
}
event.data.lastCoord = {
left : event.clientX,
top : event.clientY
}
draw();
}
function onDragEnd(){
$(document).unbind("mousemove", onDragging);
$(document).unbind("mouseup", onDragEnd);
}
function onDragStart(event){
event.data = {
lastCoord:{
left : event.clientX,
top : event.clientY
}
};
$(document).bind("mouseup", event.data, onDragEnd);
$(document).bind("mousemove", event.data, onDragging);
}
$target.bind('mousedown', onDragStart);
/*
* Draw initial view of source canvas onto target canvas
*/
$window.resize(draw);
$window.trigger("resize");
}
function draw() {
target.width = $window.width();
target.height = $window.height();
if(!scrollMax){
scrollMax = {
x: source.width - target.width,
y: source.height - target.height
}
}
targetContext.drawImage(source, scroll.x, scroll.y, target.width, target.height, 0, 0, target.width, target.height);
$('#x').html(scroll.x);
$('#y').html(scroll.y);
}
$(document).ready(init);
</script>
</head>
<body>
<div id="coords">
<p>Drag the gradient with the mouse</p>
<p>x: <span id="x"></span></p>
<p>y: <span id="y"></span></p>
</div>
<canvas id="source" width="4000" height="4000"></canvas>
<canvas id="target"></canvas>
</body>
</html>
I want to create Web pages that allow users to drag and drop images into boxes in various parts of the page, so that they can then print the pages with their images.
I want the image to automatically resize when it's dropped in the box. I combined some of the code at http://html5demos.com/file-api with some of the code at http://html5demos.com/file-api-simple to get something like I want.
In the current version of the code (below), the image width does not resize the first time you drop the image into the box, but it does the second time.
Any suggestions how I can get the image width to resize automatically the first time you drop the image into the box?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=utf-8 />
<meta name="viewport" content="width=620" />
<title>HTML5 Test</title>
</head>
<body>
<header>
<h1>HTML5 Test 1</h1>
</header>
<style>
#holder { border: 10px dashed #ccc; width: 300px; height: 300px; margin: 20px auto;}
#holder.hover { border: 10px dashed #333; }
</style>
<article>
<div id="holder"></div>
<p id="status">File API & FileReader API not supported</p>
<p>Drag an image from your desktop on to the drop zone above to see the browser read the contents of the file - without uploading the file to any servers.</p>
</article>
<script>
var holder = document.getElementById('holder'),
state = document.getElementById('status');
if (typeof window.FileReader === 'undefined') {
state.className = 'fail';
} else {
state.className = 'success';
state.innerHTML = 'File API & FileReader available';
}
holder.ondragover = function () { this.className = 'hover'; return false; };
holder.ondragend = function () { this.className = ''; return false; };
holder.ondrop = function (e) {
this.className = '';
e.stopPropagation();
e.preventDefault();
var file = e.dataTransfer.files[0],
reader = new FileReader();
reader.onload = function (event) {
var img = new Image();
img.src = event.target.result;
// note: no onload required since we've got the dataurl...I think! :)
if (img.width > 300) { // holder width
img.width = 300;
}
holder.innerHTML = '';
holder.appendChild(img);
};
reader.readAsDataURL(file);
return false;
};
</script>
</body>
</html>
I found a simple answer that I think works really well for my needs, based on a bit of CSS in http://demos.hacks.mozilla.org/openweb/DnD/dropbox.css used for http://demos.hacks.mozilla.org/openweb/DnD/.
In the code I included in my question above, I added this to the CSS code:
#holder > * {
display: block;
margin: auto;
max-width: 300px;
max-height: 300px;
}
and I deleted this:
if (img.width > 300) { // holder width
img.width = 300;
}
I tried to change font color in sticky nav bar. When scrolling down, I want to change color of nav background red to another color and font color from white to black. I tried to change font color but it can't be changed.
body{
font-size:16px;
color:#FFFFFF;
}
header {
position: fixed;
top: 0;
left: 0;
right: 0;
background-color: #D02F32;
clear: both;
width: 100%;
min-height: 87px;
}
/* ==========================================================================
Navigation Style
========================================================================== */
nav{
/*background-color:#7E7E7E;*/
padding:2px;
width:800px;
margin:0 auto;
float:right;
margin-top:1%;}
nav ul{
list-style-type:none;
text-align:center;
font-size: 1em;}
nav li{
display:inline;
padding:6px;}
nav a:hover{
color:#82ED8E;}
nav a{
text-decoration:none;
color:#FFFFFF;
font-weight:bold;}
<body>
<header class="sticky">
<div class="wrapper">
<nav class="menu-top-container">
<ul id="top-nav" class="menu">
<li>Steps</li>
<li>questions</li>
<li>answers</li>
</ul>
</nav>
</div>
</header>
</body>
Here you go (this will change nav background color to blue and font color to black when you scroll more than 210px, and will revert background color back to red and font color to white if you go back up). In case, i use jQuery implement:
$(document).ready(function(){
var scroll_pos = 0;
$(document).scroll(function() {
scroll_pos = $(this).scrollTop();
if(scroll_pos > 210) {
$("nav").css('background-color', 'blue');
$("nav a").css('color', 'black');
} else {
$("nav").css('background-color', 'red');
$("nav a").css('color', 'white');
}
});
});
You can refer more follow the link:
jquery change background color user scroll
A solution can be achieved using JS to detect a scroll event. See the below example for a jQuery implementation.
I recommend using JS to add and remove a class to the header element instead of applying inline styles. This ensures your styles can be kept together in the CSS and will make life easier when changing styles in the future.
CSS
header.compact nav {
background-color:#7E7E7E;
}
JS
var header = $('header'),
minScroll = 50; // min distance to scroll before compacting header
// Listen to scroll event
$(window).scroll(function () {
var scrollTop = $(this).scrollTop();
if (scrollTop > minScroll) {
header.addClass('compact');
}
else {
header.removeClass('compact');
}
});
It is recommended to use some sort of throttling on the scroll handler to reduce the amount of times the code fires. A post on throttling can be found here.
Include the following Jquery link to your document:
<script src="http://code.jquery.com/color/jquery.color-2.1.0.js"></script>
And use the following Jquery Code to change the background color of Nav:
<script>
$(document).ready(function(){
var scroll_pos = 0;
var animation_begin_pos = 0; //where you want the animation to begin
var animation_end_pos = 1000; //where you want the animation to stop
var beginning_color = new $.Color( 'rgb(210,50,98)' ); //we can set this here, but it'd probably be better to get it from the CSS; for the example we're setting it here.
var ending_color = new $.Color( 'rgb(0,197,209)' ); ;//what color we want to use in the end
$(document).scroll(function() {
scroll_pos = $(this).scrollTop();
if(scroll_pos >= animation_begin_pos && scroll_pos <= animation_end_pos ) {
// console.log( 'scrolling and animating' );
//we want to calculate the relevant transitional rgb value
var percentScrolled = scroll_pos / ( animation_end_pos - animation_begin_pos );
var newRed = beginning_color.red() + ( ( ending_color.red() - beginning_color.red() ) * percentScrolled );
var newGreen = beginning_color.green() + ( ( ending_color.green() - beginning_color.green() ) * percentScrolled );
var newBlue = beginning_color.blue() + ( ( ending_color.blue() - beginning_color.blue() ) * percentScrolled );
var newColor = new $.Color( newRed, newGreen, newBlue );
//console.log( newColor.red(), newColor.green(), newColor.blue() );
$('header').animate({ backgroundColor: newColor }, 0);
} else if ( scroll_pos > animation_end_pos ) {
$('header').animate({ backgroundColor: ending_color }, 0);
} else if ( scroll_pos < animation_begin_pos ) {
$('header').animate({ backgroundColor: beginning_color }, 0);
} else { }
});
});
</script>
CSS:
header.scrolledHeader ul li a {
color: ###### //color you want
}
JS:
$(window).scroll( function(e) {
var scroll = $(this).scrollTop(); // getting the current position of Scroll
if( scroll > 20 ) {
$('header').addClass('scrolledHeader');
} else {
$('header').removeClass('scrollHeader');
}
})