Im a total noob and need some help on a function which I would think for most of you would be quite simple. I am trying to do this with pure Javascript and not JQuery. I have been trying for hours and I cant get it.
What I am trying to achieve is to have a function repeat every time I click on a link.
To be more specific I currently have text that fades in when clicking a link and I would like it to always perform the fade in when I click on it (as if you were to refresh the page).
Basically: Click link (x) -- Text Fades in -- click link (x) -- same text disappears and then fades in from beginning of transition/animation (no fade out) -- repeat
I have come across something very similar on W3 schools which shows a function starting from the beginning every time you click the button: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_win_setinterval_progressbar
I thought that modifying this was the answer but because I am trying to change the opacity, I have seen that I have to add a parseFloat to the function because it is a string but I am having no success. The example is:
else { i.style.opacity = parseFloat(i.style.opacity) + .1; }
To throw another spanner in the works, I am using the opacity value from the color:rgba(0,0,0,0) to change the opacity. I thought this may be easier to find since the above example would (in my mind) bypass the parseFloat thing as you would be using i.style.color but I could not find anything.
Below is my code based on a variation of the W3 schools tutorial. I'm pretty sure that clearInterval in JS has a big part to play in what I need. Very much appreciate any help for this and please let me know if you need more clarity :)
<!DOCTYPE html>
<html>
<style>
#about {
color: rgba(10,10,10,0);
transition: color 1s linear 1s;
}
#about:target {
color: rgba(10,10,10,1);
transition: color 1s linear 1s;
}
</style>
<body>
About
<div id="div">
<p id='about'> Please help me figure this out. I really appreciate it</p>
</div>
</body>
<script>
function fadeIn() {
var elem = document.getElementById("about");
var begin = 0;
var id = setInterval(frame, 10);
function frame() {
if (begin == 100) {
clearInterval(id);
} else {
begin++;
elem.style.color = begin + '1';
}
}
}
</script>
</html>
There is a solution, which I am not going to present you, because the JS "hack" will take longer, compared to the CSS-trick: (looking for appropriate reference)
You wrap your stuff, which you want to fade in and out into a container (just making sure) and add a checkbox above it:
<label for="about">About</label>
<intput type="checkbox" name="about" id="about">
<div id="about_container"> bla-bla-bla</div>
then you style your stuff:
Hide the checkbox (the label is clickable)
make two configs for your #about_container
first: in the off mode, second in the on mode (you can comment them out for debugging purpose)
#about + #about_container
then you add the input id with pseudo-selector before the second:
#about:checked + #about_container
on your on mode, and leave the other one, like it is.
MUCH BETTER AND FASTER SOLUTION!
You should also change your question into something like:
How do I make html element appear and disappear on mouse-click or other user-interaction.
You can use transitions and then set opacity 0.5 and after some ms change it in 1 to let it fade on click and return in the older look
Edit:
Just put fadeIn() inside another function, and before the fadeIn() executon set the opacity to 0
Edit:
JS
doIt = function() {
document.getElementById("about").style.color = begin + '0';
fadeIn();
}
HTML
About
Related
Change of an attribute src seems to interupt other functions, even those not connected to the img. They don't work properly although when the line of code changing the attribute isn't called everything works perfectly fine.
I have my scripts.js that handles navigation - whenever you click header it should fade in content, change it and fade it back onto the screen.
The html of content that is to be changed:
<div id="photoContainer">
<div id="photoSection">
<img id="showedPhoto" src="img/photo1.png" />
</div>
</div>
Stylesheet:
#photoContainer
{
position: absolute;
top: 18%;
z-index: -1;
}
#photoSection
{
transition: all 0.4s ease-in-out;
}
And the most important, script:
/*
* 1. Hides photo after 0.2s of pressing button
* 2. Changes photo to another one
* 3. Shows photo
*/
function SwipePhoto(newSectionNo)
{
if(newSectionNo != currentSectionNo)
{
currentSectionNo = newSectionNo;
setTimeout(HidePhoto, 200);
setTimeout(HideContent, 200);
setTimeout(function() { changeContent(newSectionNo) }, 600);
setTimeout(ShowPhoto, 1000);
setTimeout(ShowContent, 1000);
}
}
HidePhoto, HideContent, ShowPhoto & ShowContent are just basic fadeIn/Out functions but the keypoint is the changeContent:
function changeContent(photoNo)
{
document.getElementById("showedPhoto").src = "img/photo" + photoNo + ".png";//THIS ONE
//showedPhoto.attr("src", "img/photo" + photoNo + ".png"); SAME SITUATION OCCUR WHILE USING JQUERY
content.html(text[photoNo - 1]);
sectionHeader.html(header[photoNo - 1]);
}
Without the line of code: document.getElementById("showedPhoto").src = "img/photo" + photoNo + ".png"; everything works as it should - smooth & clean (except the photo always stays the same which is not good).
But when the attribute src of img is changed all functions that should slowly fadeOut content don't seem to be working. The picture shows without any fade out effect. What is interesting, not only the image is affected as other sections also stop working, they just appear (although they worked fine before adding the line).
I fell like this is a bit more complex so if anyone could help I would be soooo grateful.
If I should add anything to help you understand the code please let me know.
Solved it!
If anyone experiences the same problem try to lower the resolution of photos, in my case they were too big to enable the website work flowlessly.
So I've got this modal that I've designed to be opened via a checkbox input, but the problem with that was that I have my divs and section arranged in such a manner that #yt-modal-cont can't be in the same container as my input due to z-index issues. So I used javascript:
if(modalToggle.checked === true) {
oLay.style.display = 'block';}
Simple enough fix, however, that's not my issue. For the animation, the route I chose was:
#yt-modal-cont {
animation: fade-before 0.3s ease-out 0s 2 alternate-reverse;
}
#keyframes fade-before {
0%{opacity:1;}
100%{opacity:0;}
}
<script>
var oLay = document.getElementById('yt-modal-cont');
var modalToggle = document.getElementById('vids');
function fadein(){
oLay.style['animation-play-state'] = 'paused';
}
function isOpen(){
if(modalToggle.checked === true) {
oLay.style.display = 'block';}
oLay.addEventListener('animationiteration', fadein);
}
}
modalToggle.addEventListener('click', isOpen);
</script>
and then for the closing function I have it setting animation-play-state=running to play through to the end, but that's not relevant. My issue is that javascript seems to be catching the end of the first iteration--and thusly adding the style--too late, as when the modal opens it's opacity is faded slightly. What's weirder, is that it's only sometimes; I open it once and it's kinda faded, I open it again and it's full opacity, then again and it's really faded... I tried adding oLay.style.opacity = 1 to the fadein function to try and override the CSS but it's still hit-or-miss. After looking at
Lag in animated image array
I feel that requestAnimationframe might be the answer, but my js newb-iness makes it so that I don't really understand what that's all about... Is that the right track or is there a different solution?
I've spent most of my morning trying to resolve how to create a scrolling marquee on an Angular app; my goal is when the dynamic text is longer than its viewport, it will scroll (repeating, meaning you don't have to wait for the entire title to scroll off the page before you see it again) but when it's short enough to display without being cut off in the viewport width, it does not scroll.
I like examples I'm seeing but need to combine them somehow and I am very beginner when it comes to adding any kind of javascript.
One is using jQuery and marquee:
$('.marquee').marquee({
duplicated: true
});
This one is great because it repeats the text and continues without it having to completely leave the screen to start again. But, my trouble comes when trying to figure out a way to add in javascript to figure out how wide that text will be; either to have it be static or scroll.
For some reason, I am unable to understand how to link to codepen or jsfiddle of the examples I've found that hit close to home. Hoping my inquiry above is enough information. I know commenters can be a bit rough—please be patient with me.
You could use text-shadow(to clone text) and animation if it is only about text.
JS will be necessary to get the width(from text lenght) of the piece to scroll and to update/insert css rule's values.
example inspired from your jsfiddle
function isElementOverflowing(element) {
var overflowX = element.offsetWidth < element.scrollWidth,
overflowY = element.offsetHeight < element.scrollHeight;
return (overflowX || overflowY);
}
// below css updated and injected . can be shorten and nicely rewritten
var element = document.getElementById('ov1');
if (isElementOverflowing(element)) {
var toscroll = element.scrollWidth;
element.style.textShadow = toscroll + 'px 0 ';
element.style.animation = 'marqueeme 5s infinite linear';
var csstyle = document.createElement('style');
csstyle.innerText = '#keyframes marqueeme {100%{ text-indent:-' + toscroll + 'px;}}';
element.appendChild(csstyle)
}
#marquee {
max-width: 15em;
overflow: hidden;
}
#ov1 {
white-space: nowrap;
margin: 0;
}
<div id="marquee">
<p id="ov1">
Yadda yadda overflowing text this line is too long oh noes!
</p>
</div>
example here is using text-indent within the animation, but negative margin-left or translateX will do the same visual.
Another example with
a text-shadow of different color
transform to see it working instead text-indent.
It also sets speed according to text length
# https://codepen.io/gc-nomade/pen/owPNZg
I'm fairly new to Javascript, so let me know if I'm doing something a little silly, but here's the gist:
I'm working with integrating a new feature into a very rigidly constructed template (I basically only get a single plaintext link). My workaround for this was to just add some jQuery that would add an onclick method that would replace the link with the element that I actually wanted to have.
$(document).ready(function(){
$("li a:contains('Search')").bind("click", replaceWithSearch);
});
function replaceWithSearch(){
var searchWrapper = constructSearchBox("");
this.parentNode.replaceChild(searchWrapper, this);
}
That all works, but I've been talking with UI people over here and they want animations for this replacement. Of course their goto is to use CSS animations, but I'm not really sure how to add a smooth fade or slide animation to the replaceChild operation. Am I thinking about this the right way? If so how exactly would I add that animation?
Using CSS animations, you'd do something like the following:
.your-selector {
animation: fadeIn 400ms ease-in-out;
}
#keyframes fadeIn {
from { opacity: 0; }
}
Here's a fiddle showing this: http://jsfiddle.net/zt3QB/. That will make it start from 0 opacity when it is injected into the DOM, and go to the default, which is 1.
If you want to use jQuery:
function replaceWithSearch(){
var searchWrapper = constructSearchBox("").css('opacity', 0);
this.parentNode.replaceChild(searchWrapper, this);
// Using setTimeout because sometimes the DOM is too fast...
setTimeout(function() {
searchWrapper.fadeTo(400, 1);
}, 0);
}
I haven't tested the jQuery one, but I've done similar things. Just finished a project using the CSS version.
Not knowing the proper way, after much research on the web I found so many different ways to do something its confusing. The way I tried, and kinda worked is the following...
My CSS
#Content {
left:0px;
top:1px;
width:988px;
z-index:1;
background-color: #FFFFFE;
}
My JS
function Gradients(id) //<- this id not used during testing, i hard coded it below
{
var getit = document.getElementById("Content");
getit.style.backgroundColor="#CCCCCC";
//alert(origcolor);
//var value = document.getElementById("Content").style.backgroundColor;
//var value = document.styleSheets[0].cssRules[0].style.backgroundColor;
}
My HTML (just a test)
<div onClick="Gradients("Content");">Gradients Test:<span>#XXXXXX</span></div>
Firebug Results - bad?
<div id="Content" style="background-color: rgb(204, 204, 204);">
WHAT I'M TRYING TO ACCOMPLISH
My goal was to read the background of an input field (each has an id) and slowly change it to red FROM the DEFAULT color in the CSS to let them know the field was incorrect.
Right now my website just slams it to red and I thought - how hard can it be to gradient a color. So, my mainpage has less clutter so I thought I would try to gradient the background of something. As with all web stuff it's messier than I thought.
I even spent a couple of hours reading up on jQuery but I don't want to pull in a whole library for this 1 tiny thing I will be doing.
Other Info
It's kinda like how THIS stackoverflow website fades from yellow to white the DIV of my question when I come here. Except mine will be in input fields. I have some commented out stuff in my JS because I was trying different things. I removed some of the things that were ugly. It works as is BUT I don't know if it's a good way to do it because firebug shows it added something to the DIV inline.
I like clean code... and my code up there seems ugly because I added something to the DIV. Can't I change the CSS value or is this the proper way to do it?
A couple of questions...
1) Proper way to do it?
2) If thats the proper way to do it how do I delete that change and have it revert back to the CSS style? Or an ugly method would be to just stick the original value I stored before performing the gradient.
3) YOUR much better clean way of doing it :)
4) Is there an elegant way to READ the value in the CSS style sheet?
The reason I didn't go with the document.stylesheets is to me....it seemed ugly... what if it's not [0]. How do I know it will always be [0]. What if it's different in different browsers? sigh. I don't fully understand the DOM. I understand what child nodes and parent nodes are but when looking through firebug it's a huge mess all over the place and I have no clue where to find things, how to insert things and I don't like modifying the DOM much anyways - i would love a simple thing like this (and yes, I am guessing on the code below - if only it could be that easy) lol...
I wish it was this easy in javascript...
$original_color = getElementById("Content").style.backgroundColor;
// loop through starting AT the original_color and gradient to red somehow
//start loop here
getElementById("Content").style.backgroundColor = newcolor;
// end loop here
Awaiting an infusion of wisdom please :)
WHAT I TRIED RECENTLY AFTER POSTING and Reading examples on here -- My JS
var RGradient = 0;
var GGradient = 0;
var GStop = 0;
var BGradient = 0;
var BStop = 100;
var idGradient;
function Gradients(id)
{
var startcolor = "#FFFFFE";
RGradient = hexToR(startcolor);
GGradient = hexToG(startcolor);
BGradient = hexToB(startcolor);
idGradient = document.getElementById(id);
window.setTimeout("GradientIt()", 10);
}
function GradientIt()
{
if (GGradient == GStop && BGradient == BStop) return;
if (GGradient > GStop) GGradient--;
if (BGradient > BStop) BGradient--;
idGradient.style.backgroundColor="#"+(RGradient).toString(16)+(GGradient).toString(16)+(BGradient).toString(16);
document.getElementById('gtest').innerHTML = "#"+(RGradient).toString(16)+(GGradient).toString(16)+(BGradient).toString(16);
window.setTimeout("GradientIt()", 5);
}
function hexToR(h) { return parseInt((cutHex(h)).substring(0,2),16) }
function hexToG(h) { return parseInt((cutHex(h)).substring(2,4),16) }
function hexToB(h) { return parseInt((cutHex(h)).substring(4,6),16) }
function cutHex(h) { return (h.charAt(0)=="#") ? h.substring(1,7) : h}
ERROR in IE
I'm getting an error in IE AFTER it turns the background to red... - Invalid Property in Line 29 which is the line with all the toString(16)'s in it above.
Can someone explain why it's giving an error in IE please? I am checking if I'm above 0 so the numbers should stay 0 or higher. The other browsers don't give an error that I can see. Once it's working I will be changing it - this is just a "hacked together" test - I'll make it more efficient later on when it's on the page I want.
I spent about an hour trying to pass variables to setTimeout before I realized I can't. UGH! lol. Globals :( Can't wait for CSS3 full compatibility in ALL browsers.
I would suggest achieving this using either css3 or jquery (a javascript library)
To do it with css3 is rather simple, this article should have all the necessary information
http://net.tutsplus.com/tutorials/html-css-techniques/css-fundametals-css-3-transitions/
To do it with jQuery you will need to download jquery and preferably have a little bit of experience with javascript although it is not generally required to pick up jQuery for simple things like this. This is the jQuery function you would want to use:
http://api.jquery.com/animate/
#content {
left:0px;
top:1px;
width:988px;
z-index:1;
background-color: #FFFFFE;
transition: 0.3s;
-moz-transition: 0.3s;
-webkit-transition: 0.3s;
}
#content:focus {
background-color: #f00;
transition: 0.3s;
-moz-transition: 0.3s;
-webkit-transition: 0.3s;
}
The above is CSS3 and works in many browsers. However IE support is (as always) lacking.
via javascript/jquery....
function animate_bg(ele, from, to) {
from += from > to ? -1 : 1;
if(!$.support.opacity){
if(from != to){
var opStr = (Math.round(from * 25.5)).toString(16);
//alert(opStr)
ele.css({background:'transparent',filter:"progid:DXImageTransform.Microsoft.gradient(startColorstr=#" + opStr + "fffff0, endColorstr=#" + opStr + "f00000)"});
}else{
ele.css({background:'transparent',filter:"none"});
}
}else{
ele.css("backgroundColor", "rgba(255, 0, 0, " + (from) / 10 + ")");
}
if(from != to)
setTimeout(function() { animate_bg(ele, from, to) }, 60);
}
and usage....
animate_bg($('...'), 8, 0);