Unable to show and hide text with fade effect on click - javascript

I was trying to create a similar effect on up and down arrows as shown in the image below but got stuck midway because of my low javascript/jquery skills.
I can't figure out how to make the text appear and then fade away on click with color change.
Here's a link to the fiddle just in case SO code snippet doesn't work
$("span").click(function() {
$("span").css("color", "grey");
$(this).css("color", "red");
});
ul > li{
list-style:none;
}
span {
cursor: pointer;
}
.fa {
font-size: 55px;
text-indent: 200px;
margin-bottom: 20px;
margin-top:30px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li><span id='select1'><i class="fa fa-long-arrow-up" aria-hidden="true"></i></span></li>
<li><span id='select2'><i class="fa fa-long-arrow-down" aria-hidden="true"></i></span></li>
</ul>
So far none of the answers have worked for me so I am asking for more help on this.
I saw this effect on reddit and I've tried many times and spent so much time but failed to get the similar effect. I'd really appreciate it if anybody could help me understand and create the exact effect.

here is my version of the solution, https://jsfiddle.net/hnk1vw6x/33/
see some explanations below.
HTML
<div class="padding-container">
<span id="rating">0</span>
<a class="arrow fa fa-arrow-up" data-animation-text="Nice!" data-value="1"></a><br/>
<a class="arrow fa fa-arrow-down" data-animation-text="Troll" data-value="-1"></a>
</div>
CSS
.padding-container {
width: 60px;
margin: 100px;
}
#rating {
float: right;
font-size: 2.1em;
width: auto;
}
a.arrow {
display: inline-block;
position: relative;
cursor: pointer;
}
a.arrow:after {
content: attr(data-animation-text);
display: block;
position: absolute;
left: 50%;
transform: translateX(-50%);
text-align: center;
width: auto;
opacity: 0;
}
a.arrow.fa-arrow-up {
color: #FF0000;
}
a.arrow.fa-arrow-down {
color: #0000FF;
}
a.arrow.fa-arrow-up:after {
bottom: 100%;
}
a.arrow.fa-arrow-down:after {
top: 100%;
}
a.arrow.animate.fa-arrow-up:after {
animation-name: slideup, bounce;
animation-duration: 3s;
}
a.arrow.animate.fa-arrow-down:after {
animation-name: slidedown, bounce;
animation-duration: 3s;
}
#keyframes slideup {
from {
bottom: 100%;
opacity: 1;
}
to {
bottom: 300%;
opacity: 0;
}
}
#keyframes slidedown {
from {
top: 100%;
opacity: 1;
}
to {
top: 300%;
opacity: 0;
}
}
#keyframes bounce {
from {
font-size: 1em;
}
3% {
font-size: 1.25em;
}
6% {
font-size: 0.75em;
}
9% {
font-size: 1em;
}
}
JavaScript
function arrowAnimationEndHandler(e) {
var arrow = e.target;
if (typeof arrow === 'undefined') {
return;
}
arrow.className = arrow.className.replace(/\banimate\b/,'');
}
function arrowClickHandler(e) {
var arrow = e.target;
if (typeof arrow === 'undefined') {
return;
}
arrow.className = arrow.className.replace(/\banimate\b/,'');
setTimeout(function () {
arrow.className += ' animate';
}, 0);
ratingUpdateBusinessLogic(arrow);
}
function ratingUpdateBusinessLogic(arrow) {
if (typeof ratingElement === 'undefined') {
return;
}
var ratingDelta = parseInt(arrow.getAttribute('data-value'), 10);
ratingElement.innerHTML = parseInt(ratingElement.innerHTML, 10) + ratingDelta;
}
var ratingElement = document.getElementById("rating");
var arrows = document.getElementsByClassName("arrow");
for (var i = 0; i < arrows.length; i++) {
arrows[i].addEventListener("animationend", arrowAnimationEndHandler, false);
arrows[i].addEventListener("click", arrowClickHandler, false);
}
Now little bit of explanation:
The problem is quite complex and author is asking for a complete solution rather then explanation of one aspect which is not clear. I decided to give an answer because then I can outline the software design steps, which might
help someone else to solve another complex problem.
In my opinion the key to complex tasks is the ability to split them in smaller, which in turn are easier to approach. Let's try to split this task into smaller pieces:
We need to draw two arrows and a number.
Up and down arrows should have different colors.
We need to draw the arrow tooltips/labels next to them.
We need to animate the arrow tooltips/labels on user interaction.
We need to apply our business logic (change the rating) on user input.
Now let's try to solve those smaller problems one by one:
We need to draw two arrows and a number. Well, HTML is our friend here and below is a trivial html code. I'm using font-awesome to draw the actual arrow icons.
<div class="padding-container">
<span id="rating">0</span>
<a class="arrow fa fa-arrow-up"></a>
<a class="arrow fa fa-arrow-down"></a>
</div>
We want our arrows to be positioned in a certain way on the screen, let's make the arrows inline-blocks, and add a line-break between them, also add some CSS to line up:
.padding-container {
width: 60px;
margin: 100px;
}
#rating {
float: right;
font-size: 2.1em;
width: auto;
}
a.arrow {
display: inline-block;
cursor: pointer;
}
Our arrows should have different colors. Again trivial CSS here. The colors are not 100% like in the gif, but that is the question of making the screenshot and picking the right color - you can do it yourself.
a.arrow.fa-arrow-up {
color: #FF0000;
}
a.arrow.fa-arrow-down {
color: #0000FF;
}
We need to draw the arrow tooltips/labels next to them. Ok, that starts to be interesting. Let's use the :after pseudo-element to draw our tooltips, because those tooltips are part of representation (and not content), they don't need to be reflected in the html structure.
I use :after and not :before because font-awesome is using before for the arrow icon rendering ;) Let's also use absolute positioning to place them relative to the actual arrows. That gives us the following CSS:
a.arrow {
position: relative;
}
a.arrow:after {
content: attr(data-animation-text);
display: block;
position: absolute;
left: 50%;
transform: translateX(-50%);
text-align: center;
width: auto;
}
a.arrow.fa-arrow-up:after {
bottom: 100%;
}
a.arrow.fa-arrow-down:after {
top: 100%;
}
Now, our tooltips are rendered just next to the arrows, and we have the possibility to control the content of them through html, e.g. for translation purposes.
Tooltips are also centered relative to the arrows.
We need to animate the arrow tooltips/labels on user interaction.
We can animate elements by javascript and we can also do that via CSS. Doing it via CSS is way more efficient, so unless we need to support really old browsers, let's stick to CSS.
We need to implement two animations, one is tooltip fading together with lift/drop and the second one is the tooltip bounce.
Let's what CSS has to offer:
a.arrow:after {
opacity: 0;
}
a.arrow.fa-arrow-up:after {
animation-name: slideup, bounce;
animation-duration: 3s;
}
a.arrow.fa-arrow-down:after {
animation-name: slidedown, bounce;
animation-duration: 3s;
}
#keyframes slideup {
from {
bottom: 100%;
opacity: 1;
}
to {
bottom: 300%;
opacity: 0;
}
}
#keyframes slidedown {
from {
top: 100%;
opacity: 1;
}
to {
top: 300%;
opacity: 0;
}
}
#keyframes bounce {
from {
font-size: 1em;
}
3% {
font-size: 1.25em;
}
6% {
font-size: 0.75em;
}
9% {
font-size: 1em;
}
}
Now we see a nice label animation straight after we load the page. All that was done without a single line of JavaScript so far.
But the task says we need to animate on user interaction.
Ok, let's now add some javascript. But before that we need a possibility to trigger the animation, let's trigger it using CSS class: animate, our CSS then changes like
a.arrow.animate.fa-arrow-up:after {
animation-name: slideup, bounce;
animation-duration: 3s;
}
a.arrow.animate.fa-arrow-down:after {
animation-name: slidedown, bounce;
animation-duration: 3s;
}
Note added animate class. If we now manually add the class to the HTML - we will see the animation again. But we need that to happen on user click, well that is easy:
function arrowClickHandler(e) {
var arrow = e.target;
arrow.className += ' animate';
}
var arrows = document.getElementsByClassName("arrow");
for (var i = 0; i < arrows.length; i++) {
arrows[i].addEventListener("click", arrowClickHandler, false);
}
Now, if we load the page and click the arrow - we will see the animation, but only once. We need to find a way to reset it. Let's remove the animate class on animation finish.
function arrowAnimationEndHandler(e) {
var arrow = e.target;
if (typeof arrow === 'undefined') {
return;
}
arrow.className = arrow.className.replace(/\banimate\b/,'');
}
var arrows = document.getElementsByClassName("arrow");
for (var i = 0; i < arrows.length; i++) {
arrows[i].addEventListener("animationend", arrowAnimationEndHandler, false);
}
Now, we can click the arrow and see an animation as many times as we want. But there is a problem, we can't restart the animation if it is going already.
For that we need a little trick:
function arrowClickHandler(e) {
var arrow = e.target;
if (typeof arrow === 'undefined') {
return;
}
arrow.className = arrow.className.replace(/\banimate\b/,'');
setTimeout(function () {
arrow.className += ' animate';
}, 0);
}
as long as we remote the animate class - we give the browser a chance to execute it's code and stop the animation and then we add the animate class again.
We need to apply our business logic (change the rating) on user input.
Here is no rocket science, we read current value and update it according to the values we have assigned to arrows:
function arrowClickHandler(e) {
...
ratingUpdateBusinessLogic(arrow);
}
function ratingUpdateBusinessLogic(arrow) {
if (typeof ratingElement === 'undefined') {
return;
}
var ratingDelta = parseInt(arrow.getAttribute('data-value'), 10);
ratingElement.innerHTML = parseInt(ratingElement.innerHTML, 10) + ratingDelta;
}
var ratingElement = document.getElementById("rating");
UPDATE:
solution with glyphicons would require replacing css/html classes fa fa-arrow-up and fa fa-arrow-down with corresponding glyphicon classes, i.e.: glyphicon glyphicon-arrow-up and glyphicon glyphicon-arrow-down. After little thinking I also decided to unbind the custom css from library classes and added custom arrow-up and arrow-down classes to simplify the icon library replacement:
<a class="arrow arrow-up glyphicon glyphicon-arrow-up" data-animation-text="Sick!" data-value="1"></a>
<a class="arrow arrow-down glyphicon glyphicon-arrow-down" data-animation-text="Suck!" data-value="-1"></a>
CSS
a.arrow.arrow-up {
.
}
a.arrow.arrow-down {
...
}
a.arrow.arrow-up:after {
...
}
a.arrow.arrow-down:after {
...
}
a.arrow.animate.arrow-up:after {
...
}
a.arrow.animate.arrow-down:after {
...
}

You can use jquery animate to get that effect. Try this
EDIT:
for exact effect use jquery easing plugin and give
easeOutElastic easing effect
$("#select1").click(function() {
$(".nice").css("display","block");
$(".nice").animate({
top: -10,
}, 500, "easeOutElastic", function() {
// Animation complete.
$(".nice").css({"opacity":"1", "top":"10px","display":"none"});
});
});
$("#select2").click(function(){
$(".troll").css("display","block");
$(".troll").animate({
top: 130,
}, 500,"easeOutElastic", function(){
$(".troll").css({"opacity":"1", "top":"120px","display":"none"});
});
});
ul > li{
list-style:none;
}
span {
cursor: pointer;
}
.fa {
font-size: 55px;
text-indent: 200px;
margin-bottom: 20px;
margin-top:30px;
}
.nice{
position:absolute;
top:10px;
text-indent :190px;
display:none;
}
.troll{
position:absolute;
top:120px;
text-indent : 190px;
display:none;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.4.1/jquery.easing.min.js"></script>
<ul>
<li>
<p class="nice">Nice</p>
<span id='select1'><i class="fa fa-long-arrow-up" aria-hidden="true"></i></span></li>
<li><span id='select2'><i class="fa fa-long-arrow-down" aria-hidden="true"></i></span>
<p class="troll">Troll</p>
</li>
</ul>

Just Add the text and show/hide it with the help of fadeout and fadein property of Jquery.
Check your updated fiddle
$("span").click(function() {
if($(this).attr('id')=='select1')
{
$("#downText").fadeOut(300);
$("#upText").fadeIn(300);
}
else
{
$("#upText").fadeOut(300);
$("#downText").fadeIn(300);
}
$("span").css("color", "grey");
$(this).css("color", "red");
});
$("fa").click(function(){
$("fa").fadeTo("slow", 0.15);
});

Add a setTimeout to make the text fade out after a few milliseconds:
$("span").click(function() {
$("span").css("color", "grey");
$(this).css("color", "red");
});
$("#select1").click(function() {
$("#down").fadeOut(300);
$("#up").fadeIn(300);
setTimeout(function() {
$("#up").fadeOut(300); // fade out the up text
}, 300); // delay of 0.3s before fading out
});
$("#select2").click(function() {
$("#up").fadeOut(300);
$("#down").fadeIn(300);
setTimeout(function() {
$("#down").fadeOut(300); // fade out the down text
}, 300); // delay of 0.3s before fading out
});
jsFiddle: https://jsfiddle.net/qze7mqj4/16/
I also added a position:absolute; to the fading text so that it doesn't make the arrows "jump" around.
You can read more about setTimeout here: http://www.w3schools.com/jsref/met_win_settimeout.asp
Basically it tells the browser to execute a function after a specified number of milliseconds, in this case, we tell the browser to fadeOut() the text after 300ms.

Related

How to make an element reset its position after mouseout event in javascript

trying to make a button like this: https://gyazo.com/9afbd559c15bb707a2d1b24ac790cf7a. The problem with the code right now is that it works as it is supposed to on the first time; but after that, instead of going from left to right as intented, it goes from right to left to right.
HTML
<div class="btn-slide block relative mx-auto" style="overflow: hidden; width: 12rem;">
<span class="z-10">View Pricing</span>
<span class="slide-bg block absolute transition" style="background-color: rgba(0,0,0,.1); z-index: -1; top: 0; left:-10rem; width: 10rem; height: 3rem;"></span>
</div>
Javascript
const btns = document.querySelectorAll(".btn-slide");
const slide = document.getElementsByClassName('slide-bg');
btns.forEach(function(btn) {
btn.addEventListener('mouseout', function () {
slide[0].style.transform = 'translateX(230%)';
slide[0].style.transform = 'none';
})
btn.addEventListener('mouseover', function() {
slide[0].style.transform = 'translateX(80%)';
}, true)
})
Unless you have to compute a value in JavaScript (like the height of an element).
Use CSS classes as modifiers (is-hidden, is-folded, is-collapsed, ...).
Using JavaScript, only add/remove/toggle the class
yourElement.addEventListener(
"mouseenter",
function (event)
{
yourElement.classList.remove("is-collapsed");
}
);
yourElement.addEventListener(
"mouseleave",
function (event)
{
yourElement.classList.add("is-collapsed");
}
);
is-collapsed is only an exemple, name it according to your class naming standard.
You're probably going to need a bit more code than what you're showing, as you have two mutually exclusive CSS things you want to do: transition that background across the "button" on mouseenter/mouseout, which is animated, and then reset the background to its start position, which should absolutely not be animated. So you need to not just toggle the background, you also need to toggle whether or not to animation those changes.
function setupAnimation(container) {
const fg = container.querySelector('.label');
const bg = container.querySelector('.slide-bg');
const stop = evt => evt.stopPropagation();
// step one: make label text inert. This is critical.
fg.addEventListener('mouseenter', stop);
fg.addEventListener('mouseout', stop);
// mouse enter: start the slide in animation
container.addEventListener('mouseenter', evt => {
bg.classList.add('animate');
bg.classList.add('slide-in');
});
// mouse out: start the slide-out animation
container.addEventListener('mouseout', evt => {
bg.classList.remove('slide-in');
bg.classList.add('slide-out');
});
// when the slide-out transition is done,
// reset the CSS with animations _turned off_
bg.addEventListener('transitionend', evt => {
if (bg.classList.contains('slide-out')) {
bg.classList.remove('animate');
bg.classList.remove('slide-out');
}
});
}
setupAnimation(document.querySelector('.slide'));
.slide {
position: relative;
overflow: hidden;
width: 12rem;
height: 1.25rem;
cursor: pointer;
border: 1px solid black;
text-align: center;
}
.slide span {
display: block;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 1;
}
.slide-bg {
background-color: rgba(0,0,0,.1);
transform: translate(-100%, 0);
transition: none;
z-index: 0;
}
.slide-bg.animate {
transition: transform 0.5s ease-in-out;
}
.slide-bg.slide-in {
transform: translate(0%, 0);
}
.slide-bg.slide-out {
transform: translate(100%, 0);
}
<div class="slide">
<span class="label">View Pricing</span>
<span class="slide-bg"></span>
</div>
And thanks to browsers being finicky with rapid succession mouseenter/mouseout events, depending on how fast you move the cursor this may not even be enough: you might very well still need a "step" tracker so that your JS knows which part of your total animation is currently active, and not trigger the mouseout code if, by the time the slide-in transition ends, the cursor is in fact (still) over the top container (or, again).
I advice you use the .on event listener
$('').on("mouseentre","elem",function(){$('').toggleclass('.classname')})
$('').on("mouseleave","elem",function(){$('').toggleclass('.classname')})
Then you can toggle css classes to your element in the function
toggle class adds the css of a class to your jquery selection, you can do it multiple times and have keyframes for animation in the css class
Keyframes are great way to implement animation and are supported on every browers

CSS Animation - Steps - to Animate Bookmark Star

I have the following code:
let animation = document.getElementById('fave');
animation.addEventListener('click', function() {
$(animation).toggleClass('animate');
});
.fave {
width: 70px;
height: 50px;
position: relative;
overflow: hidden;
}
.fave img {
position: absolute;
top: 0;
left: 0;
cursor: pointer;
animation: test_animate_reverse 1s steps(55);
}
.fave .animate {
animation: test_animate 1s steps(55);
left: -3519px;
}
#keyframes test_animate {
from {left: 0;}
to {left: -3519px;}
}
#keyframes test_animate_reverse {
from {left: -3519px;}
to {left: 0;}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section class="fave"><img src="https://cssanimation.rocks/images/posts/steps/twitter_fave_rectangle.png" id="fave"></section>
The target image is: https://cssanimation.rocks/images/posts/steps/twitter_fave_rectangle.png (albeit already modified so that all the images are positioned horizontally).
The result is quite satisfactory already. However, I have concerns:
As can probably be seen, my star always animates from the last frame of said image to the first frame whenever I refresh the browser window. If possible, I'd like it to not do that when I first refresh the window and only reverse-animate when I toggle it from 'active' to 'not active'.
I feel like using two #keyframes just to reverse an animation that is exactly the same is kind of inefficient. Is there a way to achieve the same effect without having to make an additional reverse #keyframes?
Is there a way for me to achieve the same effect without specifying the size of section explicitly when said section does not have a parent?
When I click quickly a few times on said image, if possible, I'd like it to finish its current animation first before proceeding to the next one. With my code now, preceding animations are immediately ended when a new animation is run.
EDIT
I've tried to not use the reverse #keyframes by changing to the following:
.fave img {
position: absolute;
top: 0;
left: 0;
cursor: pointer;
animation: test_animate .7s steps(55);
animation-direction: reverse;
}
What happened is the animation completely vanished.
Why not use the code from the actual tutorial where you got the image. It uses transition rather than animation and seems neater.
It will automatically reverse the animation too with the transition applied to the element.
You can set a disabled flag and use setTimeout() to prevent multiple clicks before the animation has finished.
var click_disabled = false;
$('.fave').click(function() {
if (click_disabled) {
return; // do nothing
}
$(this).toggleClass('faved');
// Set correct aria-label
var label = $(this).attr('aria-label') == 'Favourite' ? 'Unfavourite' : 'Favourite';
$(this).attr('aria-label',label);
click_disabled = true;
// Timeout value should match transition length
setTimeout(function(){
click_disabled = false;
}, 1000);
});
.fave {
background: none;
border: 0;
padding: 0;
width: 70px;
height: 45px;
background: url(https://res.cloudinary.com/shanomurphy/image/upload/v1547543273/fave_ltre0q.png) no-repeat;
background-position: 0 0;
transition: background 1s steps(55);
outline: 0;
cursor: pointer;
}
.fave.faved {
background-position: -3519px 0;
}
<button class="fave" aria-label="Favourite"></button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Forcing mobile devices to activate :hover CSS properties on first touch and activate link on second touch

: )
So, I'm trying to solve a hover effect issue. I have tooltips on some of my links. Code looks like this:
<a href="https://wikipedia.org/wiki/Space_Shuttle_Atlantis">
<h6 class="has-tip">Space Shuttle
<p class="tip">The space shuttle was invented by Santa Claus</p>
</h6>
</a>
And the CSS is a bit more involved:
.tip {
display: block;
position: absolute;
bottom: 100%;
left: 0;
width: 100%;
pointer-events: none;
padding: 20px;
margin-bottom: 15px;
color: #fff;
opacity: 0;
background: rgba(255,255,255,.8);
color: coal;
font-family: 'Ubuntu Light';
font-size: 1em;
font-weight: normal;
text-align: left;
text-shadow: none;
border-radius: .2em;
transform: translateY(10px);
transition: all .25s ease-out;
box-shadow: 2px 2px 6px rgba(0, 0, 0, 0.28);
}
.tip::before {
content: " ";
display: block;
position: absolute;
bottom: -20px;
left: 0;
height: 20px;
width: 100%;
}
.tip::after { /* the lil triangle */
content: " ";
position: absolute;
bottom: -10px;
left: 50%;
height: 0;
width: 0;
margin-left: -13px;
border-left: solid transparent 10px;
border-right: solid transparent 10px;
border-top: solid rgba(255,255,255,.8) 10px;
}
.has-tip:hover .tip {
opacity 1;
pointer-events auto;
transform translateY(0px);
}
Now, on desktop this works wonderfully. You hover over the tiny title and you get a pretty looking tooltip, then if you click anywhere on the title or tooltip (unless you decide to put yet another link in the paragraph which works separately and nicely) you activate the link. Yay : )
Now on mobile, the whole thing gets funky. Touching just activates the link. If you have slow internet, or iOS, you might glimpse the tooltip just as the next page loads.
I would like the following behavior:
User taps on tiny title (h6) which has class (has-tip)
If this is the first tap, the tooltip shows, and nothing else happens. 3)
If the tooltip is already showing when they tap (as in a subsequent
tap) then the link is activate and the new page loads.
Any ideas how I might implement this? No jQuery if possible.
One way to do it is to save a reference to the last clicked has-tip link and to apply a class to it which forces the tip to show. When you click on a link and it matches the the last one clicked, you let the event pass.
EDIT: oh, I forgot to mention you might need a classList shim for old IE.
JSFiddle link.
HTML
<a href="http://jsfiddle.net/1tc52muq/5/" class="has-tip">
JSFiddle<span class="tip">Click for some fun recursion</span>
</a><br />
<a href="http://google.com" class="has-tip">
Google<span class="tip">Click to look for answers</span>
</a>
JS
lastTip = null;
if(mobile) {
var withtip = document.querySelectorAll(".has-tip");
for(var i=0; i<withtip.length; ++i) {
withtip[i].addEventListener("click", function(e) {
if(lastTip != e.target) {
e.preventDefault();
if(lastTip) lastTip.classList.remove("force-tip");
lastTip = e.target;
lastTip.classList.add("force-tip");
}
});
}
}
CSS
.has-tip {
position: abolute;
}
.tip {
display: none;
position: relative;
left: 20px;
background: black;
color: white;
}
.has-tip:hover .tip, .force-tip .tip {
display: inline-block;
}
Edit: Just wanted to say that Jacques' approach is similar, but much more elegant.
On touch devices, you'll need to make a click/tap counter:
1) On first tap of any link, store the link and display the hover state.
2) On another tap, check to see if it's the same as the first, and then perform the normal tap action if it is. Otherwise, clear any existing hovers, and set the new tap target as the one to count.
3) Reset / clear any hovers if you tap on non-links.
I've made a rudimentary JSFiddle that console.logs these actions. Since we're not using jQuery, I didn't bother with adding/removing CSS classes on the elements.
Also, sorry about not writing taps instead of clicks.
var clickTarget;
var touchDevice = true;
if(touchDevice) {
var links = document.getElementsByTagName('a');
for(var i=0; i<links.length; i++) {
links[i].onclick = function(event) {
event.stopPropagation();
event.preventDefault(); // this is key to ignore the first tap
checkClick(event);
};
};
document.onclick = function() {
clearClicks();
};
}
var checkClick = function(event) {
if(clickTarget === event.target) {
// since we're prevent default, we need to manually trigger an action here.
console.log("Show click state and also perform normal click action.");
clearClicks();
} else {
console.log("New link clicked / Show hover");
clickTarget = event.target;
}
}
var clearClicks = function() {
console.log("Clearing clicks");
clickTarget = undefined;
};
http://jsfiddle.net/doydLt6v/1/

Firefox Scrolling Bug When Changing :after Contents

I want to change pseudo elements on a container based on its scroll position. I made a jsfiddle to demonstrate the bug I stumbled upon: http://jsfiddle.net/krzncu1k/1/
The :after-element shows the current scroll status ("upper half" or "lower half"). Its content changes by toggling the classes .upper-half and .lower-half based on scroll position:
.upper-half:after {content:'upper half'; top:0;}
.lower-half:after {content:'lower half'; bottom:0;}
The corresponding JS:
$wrap.toggleClass('upper-half', isUpper).toggleClass('lower-half', !isUpper);
The bug happens when using Firefox and scrolling via dragging the scrollbar (not via mousewheel!). If you drag it and cross the middle (where the class changes from .upper-half to .lower-half) you suddenly can't drag any further.
Any ideas on why this behavior occurs and how to fix it?
No idea why this occurs in Firefox, but I do have a workaround. Create the upper half with :before, the lower half with :after and hide and show with opacity when the class changes. Might as well throw in a smooth transition as well. The bug is prevented because the position is not changing.
(you could also use display: none instead of opacity, but it cannot be transitioned)
Working Example
$(function() {
var $wrap = $('.wrap'),
$ul = $('ul'),
ulHeight = $ul.height();
$ul.scroll(function(e) {
var isUpper = (this.scrollTop + ulHeight / 2) / this.scrollHeight <= 0.5;
$wrap.toggleClass('upper-half', isUpper).toggleClass('lower-half', !isUpper);
});
});
ul {
overflow: auto;
max-height: 200px;
background-color: #ddd;
}
li {
font-size: 200%;
}
.wrap {
position: relative;
width: 200px;
}
.wrap:before,
.wrap:after {
position: absolute;
left: 0;
width: 100px;
height: 40px;
background-color: rgba(128, 128, 128, 0.3);
text-align: center;
color: white;
line-height: 40px;
transition: opacity 0.5s;
}
.wrap:before {
content: 'upper half';
top: 0;
}
.wrap:after {
content: 'lower half';
bottom: 0;
}
.upper-half:after {
opacity: 0;
}
.lower-half:before {
opacity: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="wrap upper-half">
<ul>
<li>Some</li>
<li>Random</li>
<li>Bullet</li>
<li>Points</li>
<li>Just</li>
<li>To</li>
<li>Make</li>
<li>This</li>
<li>Awesome</li>
<li>List</li>
<li>A</li>
<li>Little</li>
<li>Longer</li>
<li>And</li>
<li>Longer</li>
<li>And</li>
<li>Longer</li>
</ul>
</div>

How can I get only the specific H3 I am hovering over to show and not all of them?

I am trying to have text appear over each image as the user hovers over that specific image. I don't want all of the text for every image to appear when a user hovers over one image. I have it where only the one photo becomes opaque but right now the text shows up for every image when hovering over any image.
HTML:
<div class="image">
<img class="projectImage" src="images/peralta.png" alt="">
<h3 class="hiddenH3">This is a test!</h3>
</div>
SCSS:
.image {
position: relative;
width: 100%;
.projectImage {
width: 100%;
transition: all 0.5s ease-in;
}
.hiddenH3 {
display: none;
position: absolute;
top: 45%;
width: 100%;
}
}
JS:
$('.projectImage').on("mouseover", function() {
$(this).closest('.projectImage').addClass("coolEffect");
$('.hiddenH3').fadeIn(1000);
});
$('.projectImage').on("mouseout", function() {
$(this).closest('.projectImage').removeClass("coolEffect");
$('.hiddenH3').fadeOut(1000);
});
Use .next along with this
$('.projectImage').on("mouseover", function() {
$(this).addClass("coolEffect");
$(this).next(".hiddenH3").fadeIn(1000);
});
$('.projectImage').on("mouseout", function() {
$(this).removeClass("coolEffect");
$(this).next(".hiddenH3").fadeOut(1000);
});
You can also remove .closest(".projectImage") as this refers to that image.
Why don't you do this with CSS? Since the selectors needed are very old and entrenched, you can do something like this:
.projectImage + h3 {
transition: opacity 1000ms;
opacity: 0;
}
.projectImage:hover + h3 {
opacity: 1;
}
This will fade in your h3 when you hover over the project image, as long as you structure it in that way (i.e., ing, then h3). You can also remove the classes cooLEffect and hiddenh3 as we have defined that by only targeting the h3 that comes after a project image.
The fancy transition effect will only work on modern browser, but older browsers gracefully degrade.
Edit: SASS / LESS
.image {
.projectImage {
& + h3 {
transition: opacity 1000ms;
opacity: 0;
}
&:hover + h3 {
opacity: 1;
}
}
}

Categories

Resources