I have a JavaScript function to display images in a slideshow by changing the source. I have tried to create smth to include a fadeIn effect but I think it was catastrophic..Here is my JavaScript function. I don't need a complete answer, just some tips helping me to achieve that. I'm a very beginner in JavaScript but I want to learn it well. If there is a way to do that without jQuery, it would be nice, or to include jQuery directly inside this function will be the best.
{
function nextImage() {
if (currentImage < 5) {
currentImage = currentImage + 1;
} else {
currentImage = 1;
}
document.getElementById('image').src = 'images/' + currentImage + '.jpg';
}
}
Naturally, what the fadein will be adapt as a fadeout in the opposite function, but I think this example can help a newbie like me.
with jquery it would go something like this:
function nextImage() {
if (currentImage < 5) {
currentImage = currentImage + 1;
} else {
currentImage = 1;
}
$("#image").fadeOut('fast', function() {
$("#image").attr('src','images/' + currentImage + '.jpg');
$("#image").fadeIn('fast');
});
}
I don't think it's a stupid question, though for whatever reason my own questions get downvoted, go figure! (end rant)
You might consider if you are able to use CSS there are CSS3 fade transitions that you can try.
If you were to do it in Javascript I would probably use jQuery to do it because those functions are already there and all you have to do is use .show('slow') and .hide('slow') and that argument 'slow' will automatically do the animation for you.
http://api.jquery.com/show/
Otherwise if you want to write it from scratch, then you can probably look at the jQuery source code to see how the actual animation effect is done.
You should JQuery as they have made it very easy to do the effects:
http://api.jquery.com/category/effects/fading/
Take a look at their examples and documentations
Here is an example:
Examples:
Example: Animates hidden divs to fade in one by one, completing each animation within 600 milliseconds.
<!DOCTYPE html>
<html>
<head>
<style>
span { color:red; cursor:pointer; }
div { margin:3px; width:80px; display:none;
height:80px; float:left; }
div#one { background:#f00; }
div#two { background:#0f0; }
div#three { background:#00f; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<span>Click here...</span>
<div id="one"></div>
<div id="two"></div>
<div id="three"></div>
<script>
$(document.body).click(function () {
$("div:hidden:first").fadeIn("slow");
});
</script>
Some tips on how to start using JQuery:
var a = $(document); // <-- set the hole document to variable a
var b = $("#myid"); // <-- set the element that has id="myid" to variable b
var c = $(".myclass"); // <-- set the element(s) that has class="myclass" to variable c
var d = $("img"); // <-- set the img element(s) to variable d
Use Chrome Web Inspector or Firebug to debug your JavaScript code
Related
Ok so I've revised the markup/code to make it easier to understand. Using JavaScript I want to know how to create a text slider that changes a paragraph in html5 either "forwards" or "backwards" on click?
I only want one div to show at a time and the first div (div_1) needs to be visible at the beginning as a default setting. I also want to be able to add more text divs to it in the future. I'm new to JavaScript so I want to keep it as simple as possible.
I've had a go creating it in JavaScript which hasn't worked, I'm not sure if I'm going about this the right way.
<!DOCTYPE html>
<html lang="en">
<head>
<style type="text/css">
.showHide {
display: none;
}
</style>
<script type="text/javascript">
var sdivs = [document.getElementById("div_1"),
document.getElementById("div_2"),
document.getElementById("div_3"),
document.getElementById("div_4")];
function openDiv(x) {
//I need to keep div_1 open as a starting point
sdivs[0].style.display ="block";
var j;
for (var j = 0; j < sdivs.length; j++) {
if (j === x) {
continue;
}
else {
sdivs[j].style.display = "none";
}
}
}
</script>
<title>text</title>
</head>
<body>
forward
backwards
<div id="text_holder">
<div id="div_1" class="showHide">One</div>
<div id="div_2" class="showHide">Two</div>
<div id="div_3" class="showHide">Three</div>
<div id="div_4" class="showHide">Four</div>
</div>
</body>
</html>
When dealing with multiple elements like this, I've found CSS alone to be insufficient (though its brilliant for modifying simple hover states or whatever). This one method here is pretty simple and specific to this one set of markup (so modify as you see fit). More importantly - its to illustrate how to set up a simple javascript "class" to handle your logic.
http://jsfiddle.net/1z13qb58/
// use a module format to keep the DOM tidy
(function($){
// define vars
var _container;
var _blurbs;
var _blurbWidth;
var _index;
var _clicks;
// initialize app
function init(){
console.log('init');
// initialize vars
_container = $('#text_holder .inner');
_blurbs = $('.blurb');
_blurbWidth = $(_blurbs[0]).innerWidth();
_clicks = $('.clicks');
_index = 0;
// assign handlers and start
styles();
addEventHandlers();
}
// initialize styles
function styles(){
_container.width(_blurbs.length * _blurbWidth);
}
// catch user interaction
function addEventHandlers(){
_clicks.on({
'click': function(el, args){
captureClicks( $(this).attr('id') );
}
});
}
// iterate _index based on click term
function captureClicks(term){
switch(term){
case 'forwards':
_index++;
if(_index > _blurbs.length - 1){
_index = 0;
}
break;
case 'backwards':
_index--;
if(_index < 0){
_index = _blurbs.length - 1;
}
break;
}
updateView();
}
// update the _container elements left value
function updateView(){
//_container.animate({
//'left' : (_index * _blurbWidth) * -1
//}, 500);
_container.css('left', ((_index * _blurbWidth) * -1) + 'px');
}
init();
})(jQuery);
I'm using jQuery to handle event binding and animation, but, again - there are lots of options (including a combination of vanilla javascript and CSS3 transitions).
I'll note also that this is all html4 and css2 (save your doctype).
Hopefully that helps -
Trying to do a simple fade in using the opacity property of an h1 element. I'm learning javascript, so would like to try this using plain javascript (yes, I know it is much easier using jQuery).
Pasting only relevant snippets:
<body onload="fadeIn()">
...
<div class = "container">
<div class = "row">
<div class = "col-md-3">
<img class = "img-responsive" src="icons/Website_Logo.png">
</div>
<div class = "col-md-9 page-header">
<h1 id="welcomeHeader" style="opacity:0">
Welcome to the world!
</h1>
</div>
</div>
</div>
...
<script>
function fadeIn() {
var el = document.getElementById("welcomeHeader");
var op = parseFloat(el.style.opacity);
var timer = (function () {
if(op >= 1.0)
clearInterval(timer);
op += 0.1;
el.style.opacity = op;
}, 50);
}
</script>
</body>
Help is much appreciated! Thanks!
jsFIDDLE
You need to call the setInterval function first in order to invoke a timer. Rest is fine. Here is a working fiddle
Code Snippet:
function fadeIn() {
var el = document.getElementById("welcomeHeader");
var op = parseFloat(el.style.opacity);
var timer = setInterval(function () {
console.log('here');
if(op >= 1.0)
clearInterval(timer);
op += 0.1;
el.style.opacity = op;
}, 50);
}
You need to change your function to use setInterval like so:
var timer = setInterval(function () { // notice the setInterval added.
if(op >= 1.0)
clearInterval(timer);
op += 0.1;
el.style.opacity = op;
}, 50);
Notes:
I give you this answer to help you LEARN javascript as you mentioned, otherwise,
it would be better done with pure css of course.
Also, make sure your opacity is set to 0 in your css as a starting point.
You don't need a timer for this - all you need to do is change the class. Here's an example:
the CSS:
element{
/* whatever styles you have */
}
element_faded{
transition: opacity .5s;
opacity: 50%; /* or whatever values you want */
}
the javascript
var element = document.getElementById('element');
// in order to trigger the fade, just change the class
element.className = "element_faded";
In the transition will happen between the values of the original and new class, so if you want a fade-in, have the original opacity be 0% and the new one be 100% or something higher than zero, depending on what you want the final opacity to be. Also, remember that the transition characteristics are determined by the transition attribute in the new class.
Doing this without CSS will just make things more complicated unless you need to do something more sophisticated than just plain fading in or out. If that's the case, then use setInterval or perhaps even something like requestAnimationFrame if you're feeling adventurous.
Honestly, this isn't really the kind of thing you need to learn when first learning javascript. Eventually this will be really easy once you get some confidence under your belt doing things that work more easily in javascript (setTimeout and the like can have their own weird caveats). Try to set a meaningful, practical goal and fulfill it first, using whatever mix of javscript/css/html you can and you'll soon have the basics down well enough to find things like this obvious.
I have a div id="coding" set on height:300px on CSS.
when I click another div id="menu", I want #coding to change it's height to 800px. I managed to do that like this
<script>
function changec() {
document.getElementById('coding').style.height = "800px";
}
</script>
Now, when click the #menu again, I want the height to get back to it's original 300px value. Can someone help? The code is:
HTML
<div id="coding">
<div id="menu" onclick="changec()">≡</div>
...
</div>
CSS
#coding{
...
height:300px;
}
Simple check if the value is set - remove it (then CSS height will take over).
function changec() {
var xDiv = document.getElementById('coding');
if (xDiv.style.height == '')
xDiv.style.height = '800px'
else
xDiv.style.height = ''
}
Demo: http://jsfiddle.net/ygalanter/BLE6N/
one of the solution for your problem is as follows:
First count how many times you click on #menu
now depending on your expectation you can change the javascript as follows
<script type="text/javascript">
var count = 0;
function changec() {
count++;
if(count%2==1)
document.getElementById("coding").style.height = "800px";
else
document.getElementById("coding").style.height = "300px";
}
</script>
Another alternative solution is
<script type="text/javascript">
function changec() {
var currentheight = document.getElementById('coding').clientHeight;
if (currentheight == 300)
document.getElementById('coding').style.height = "800px";
else if (currentheight == 800)
document.getElementById('coding').style.height = "300px";
}
</script>
Not sure why you tagged jQuery since you didn't use it, but still...Considering the possibility that you are willing to use/learn it, I created a jsFiddle for it: http://jsfiddle.net/Tm2Hd/.
CSS:
#coding{
border:1px solid black; /*optional: Keep track of your div's expand*/
height:300px;
}
#coding.larger{
height:800px;
}
JS:
function changeHeight() {
if($('#coding.larger').length>0)
{
$('#coding').removeClass("larger");
}
else
{
$('#coding').addClass("larger");
}
}
HTML
<div id="coding">
<!--<div onclick="changeHeight()">≡</div>
Personally, I don't suggest using divs as clickable objects... Why don't you use buttons instead?
-->
<button onclick="changeHeight()">≡</button>
...
</div>
My solution to your problem is: Create a new class named larger, pointing to your div, and toggle between this and the original whenever you click the button.
I made a div and a button. Made a function that changes the opacity of the div in JavaScript.
Then I made an array of opacities and a for loop and kept the opacity that I want on each loop. But I don't know what is wrong?
Please don't give me suggestions like I should use jQuery or some other library. I want to do it in JavaScript!(without any library)
Here see my code:-
<!DOCTYPE html>
<html>
<head>
<link rel="icon" type="image/jpg" href="http://s3images.coroflot.com/user_files/individual_files/original_240004_eFk2sUc1K3KyXWz60vHrALo5H.jpg">
<title>JavaScript</title>
<style>
body
{
font-family:ebrima;
color:black;
}
#box
{
height:100px;
width:100px;
background:red;
opacity:1;
}
</style>
</head>
<body id="mainBody">
<div id="box"></div>
<button type="button" id="b" onClick="lessTheOppacity()">OPACITY</button>
<script>
function lessTheOppacity()
{
var box = document.getElementById("box");
var oppArray = ["0.9", "0.8", "0.7", "0.6", "0.5", "0.4", "0.3", "0.2", "0.1", "0"];
for (var x = 0; x < 10;x++)
{
box.style.opacity=oppArray[x];
}
}
</script>
</body>
</html>
function lessTheOppacity()
{
var box = document.getElementById("box");
var oppArray = ["0.9", "0.8", "0.7", "0.6", "0.5", "0.4", "0.3", "0.2", "0.1", "0"];
var x = 0;
(function next() {
box.style.opacity = oppArray[x];
if(++x < oppArray.length) {
setTimeout(next, 100); //depending on how fast you want to fade
}
})();
}
Explanation:
(1) next is a function that will advance us to the next opacity. I chose its name arbitrarily.
(function next() {
...
})();
defines the function and then calls it immediately.
(2) ++x means "increase the value of x by one and give me that value". We use it to increment x and to check whether we need to continue fading the element.
(3) We want the fade to happen gradually, over time. Yours happens all at once, so the user only sees the last one, "0.0".
Here, the setTimeout waits 100 milliseconds before calling the next function and going to the next opacity.
See setTimeout documentation for more info.
Futher notes:
A more flexible approach would be to allow the fade time to vary, and to calculate the steps accordingly, not always having ten, or to have a non-linear fade. But that is more complicated, and it is why people usually use jQuery.
// this does a linear fade
function fade(element, duration) {
var start = new Date;
(function next() {
var time = new Date - start;
if(time < duration) {
box.style.opacity = 1 - time / duration;
requestAnimationFrame(next);
} else {
box.style.opacity = '0';
}
})();
}
JSFiddle
Also, if you can depend on the browser supporting CSS3 transitions, I would look into doing it that way. It is cleaner and generally preferred.
You can't. But you can use jQuery instead JavaScript
<!DOCTYPE html>
<html>
<head>
<link rel="icon" type="image/jpg" href="http://s3images.coroflot.com/user_files/individual_files/original_240004_eFk2sUc1K3KyXWz60vHrALo5H.jpg">
<title>JavaScript</title>
<style>
body
{
font-family:ebrima;
color:black;
}
#box
{
height:100px;
width:100px;
background:red;
opacity:1;
}
</style>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
</head>
<body id="mainBody">
<div id="box"></div>
<input type="button" class="opacity" value="opacity" />
<script>
$(".opacity").click(function () {
$('#box').toggle("slow");
});
</script>
</body>
</html>
It's more easy. You can use toggle(), slideToggle() or fadeToggle() functions for animations.
Don't iterate through an array of values that you can easily calculate. This should show you how it works:
var opacity = 1;
function lto() {
var box = document.getElementById('box');
opacity -= 0.1;
if (opacity < 0)
{opacity = 1; return;}
box.style.opacity = opacity;
setTimeout(lto, 100);
}
In your case, you run from full opacity to transparent without the browser getting even a chance to draw it anew. So instead of the function above, use some asynchronous event ( setTimeout(…)) to actually call the lto function
I'm writing an auction template for eBay, hoping that eBay would allow it. Apparently they don't because jquery has things like string.replace() etc.
The code is very basic.
$(document).ready(function(){
function changeImage(){
if($("#coin1").css("display") == "none"){
$("#coin1").fadeIn("slow");
}else{
$("#coin1").fadeOut("slow");
}
};
setInterval ( changeImage, 5000 );
});
I basically need to rewrite it in plain Javascript...
If you can live without the fading effect, it should be pretty straightforward:
function changeImage() {
var image = document.getElementById('coin1');
image.style.display = (image.style.display == 'none') ? 'block' : 'none';
}
setInterval(changeImage, 5000);
While fading is cool and all, it's really makes the code a lot more complicated, when we not allowed to use external libraries. Basically, you will need to deal with additional timers, firing with very short intervals, changing the opacity of the target element on each callback.
If you really want fading, see "Javascript Tutorial - Simple Fade Animation".
The most basic of fading, not cross-browser compatible (try in Chrome):
<div id="x" style="background-color: yellow;">
fade me out
</div>
<script type="text/javascript">
var val = 1.0;
function fade()
{
document.getElementById('x').style.opacity = val;
val -= 0.1;
if (val != 0)
{
setInterval(fade, 100);
}
}
</script>
You could use classList.toggle on your element:
<style>
.hidden { display: none !important; }
</style>
<script>
function toggle() {
document.getElementById('elem').classList.toggle('hidden');
}
</script>
Toggle element
<p id="elem">lorem ipsum quid modo tralala</p>
I had issues with the interval approach. This is what I came up with.
function showHide() {
var element = document.getElementById('hiddenDetails');
element.classList.toggle("hidden");
}
.hidden {
display: none;
}
.show {
display: block;
}
Get Details
<div id="hiddenDetails" class="hidden">What you want to show and hide</div>