How do I animate two letters swapping? - javascript

I am trying to make a website where hovering over a misspelling consisting of transposition of two letters corrects it, like so:
var swap = document.querySelector('.swap');
swap.addEventListener('mouseover', swapIn);
swap.addEventListener('mouseout', swapOut);
function swapIn(e) {
e.target.parentNode.firstChild.classList.toggle('shifted-right');
e.target.parentNode.lastChild.classList.toggle('shifted-left');
}
function swapOut(e) {
e.target.parentNode.firstChild.classList.toggle('shifted-right');
e.target.parentNode.lastChild.classList.toggle('shifted-left');
}
body {
font-size: 24px;
}
.swap {
display: inline;
}
span {
-webkit-transition: all 0.3s linear;
-moz-transition: all 0.3s linear;
-o-transition: all 0.3s linear;
transition: all 0.3s linear;
}
.shifted-right {
margin-left: 20px;
color: blue;
}
.shifted-left {
margin-left: -25px;
color: red;
}
E<div class="swap" id="swap"><span class="left-swap" id="ls">q</span><span class="right-swap" id="rs">c</span></div>uis me vivit fortunatior?
However, as you can see, the letters don't swap well, and besides, I don't want to calculate the precise margins for each different letter width.
What's a better approach to doing this?

Switching two letters in the same word can be done by calculating their relative position to their parent with the offsetLeft property.
Subtract the values from each other and use Math.abs to keep the integer a positive number. This number is the distance between the two letters. One letter has to go the entire distance to the left and the other the same distance to the right to switch positions. Set the a CSS Variable with the distance so we can pass the calculation to CSS.
In CSS we can use the :hover pseudo selector to set styles on hover and use the CSS Variable to make the proper transition. And instead of targeting the hover on a letter, target the hover on the entire word.
Instead of margin, use transform; this property does not mess with the layout and will only any manipulate the element that is targeted.
const word = document.querySelector('.word');
const [e, a] = word.querySelectorAll('.letter');
const distance = Math.abs(e.offsetLeft - a.offsetLeft);
word.style.setProperty('--distance', `${distance}px`);
.word {
display: inline-block;
padding: 15px;
position: relative;
font-size: 32px;
background-color: #f7f7f7;
border: 1px dashed #d0d0d0;
border-radius: 3px;
cursor: help;
}
.word .letter {
display: inline-block;
color: red;
transition: color 500ms ease-in-out, transform 500ms ease-in-out;
}
.word:hover .letter {
color: green;
}
.word:hover .letter:first-of-type {
transform: translate(var(--distance), 0);
}
.word:hover .letter:last-of-type {
transform: translate(calc(var(--distance) * -1), 0);
}
<span class="word">
App<span class="letter">e</span>r<span class="letter">a</span>nt
</span>

Related

Is there a way to use css with an If/else condition?

I am making a memory game for school.
My issue right now is, you can spam click everything and everything will show.
whenever you have the wrong pair the cards make the class "red" and they turn red in the css code. But you're still able to click the other cards and a few turn back to normal again after 600ms, some just stay and don't turn back.
is it possible to use an if/else condition for css? If there are "red" cards, the pointer event for normal cards are none. You can play the game here and test the issue yourself: https://memory-20.815374.repl.co
Fixing it without If/else is fine too. Using if/else is just the first thing that comes in my head.
here is the code for CSS:
.card.clicked {
background-color: orange;
pointer-events: none;
}
.card.checked {
background-color: lightgreen;
visibility: hidden;
transition: visibility 0s linear 300ms, opacity 300ms;
}
.card.clicked img,
.card.checked img {
opacity: 1;
}
.card.red {
background-color: #f15f5f;
}
.card {
height: 120px;
width: 100px;
background-color: #ff5cbb;
border-radius: 10px;
display: grid;
place-items: center;
cursor: pointer;
transition: 0.3s all ease;
}
Here is the JavaScript code:
} else {
const incorrectCards = document.querySelectorAll(".card.clicked");
incorrectCards[0].classList.add("red");
incorrectCards[1].classList.add("red");
setTimeout(() => {
incorrectCards[0].classList.remove("red");
incorrectCards[0].classList.remove("clicked");
incorrectCards[1].classList.remove("red");
incorrectCards[1].classList.remove("clicked");
}, 600);

How to to hide text and show on click

I have one dark division box I want to develop such thing when you click and hold mouse over div one round shape div will transparent and it will show hidden sentence under that dark div.
give that div box a class e.g darkBox then in css
u can also give "active" property for clicking
border-radius can make it round, if u give 50% it will make it circle, if u want corner edges round or curved u can give values less than this
.darkBox:hover{
background-color: transparent;
border-radius: 50%;
}
I hope this helps ,if not can you please tell me what u exactly require
Key point:
A round shape can easily be made by using border-radius: 50%.
The pseudo-class :hover is what activates the alternate state.
The pseudo-class :before (and :after) can insert into an element some text.
The extra fading effects were done with transition.
.orb {
font-size: 3em;
border: 2px solid black;
border-radius: 50%;
height: 1.5em;
width: 1.5em;
text-align: center;
cursor: pointer;
background-color: black;
}
.orb:before {
content: '\2620';
transition: opacity 3.5s ease-in, color 4s linear;
opacity: 0;
color: transparent;
}
.orb:hover:before {
content: '\2620';
opacity: 1;
color: white;
}
.cap:after {
content: '';
transition: opacity 3.5s ease-in, color 4s linear;
opacity: 0;
color: transparent;
}
.orb:hover .cap:after {
content: 'The skull and crossbones is actually a font character';
opacity: 1;
color: red;
font: 400 16px/.3 'Palatino Linotype';
white-space: nowrap;
}
<figure class="orb">
<figcaption class="cap"></figcaption>
</figure>

Adding Parent Selectors To CSS block using jQuery

So we have an email builder that allows the client to create their own custom color schemes. In additon to pre-defined fields we allow them to enter their own custom CSS block to modify their color schemes.
The problem is we NEED to put a parent selector before each rule. So for instance:
p {font-size:12px;}
will need to become
.parent_selector p {font-size:12px;}
Is there anyway to programmatically add these parent selectors to EACH CSS rule? As an example use case let's say this is the custom css provided by the client:
p {font-size:12px; font-weight:bold}
.description {color:#cccccc; line-height:1.2em;}
#header {padding:bottom:12px}
.buttons .button {padding:12px; background:#112233;}
.buttons a {text-decoration:none;}
I would need a parent selector before each rule. I've considered searching for brackets and adding text accordingly but it got too complicated. Another option (which I don't like) is creating a dummy selector and doing a string replace. Here is an example:
.placeholder p {font-size:12px;}
will need to become
.parent_selector p {font-size:12px;}
Thanks in advance!
You could try to inject their code into something like the less preprocessor and compile before sending to the server. or create your own parser to prepend the parent selector to the classes provided. This would probably need work for the different formats that could be input by your users.
edit: on second thought don't leave it to chance. remove all double whitespace characters and you will get a consistent formatting and minification for free.
function addParentSelector( parentSelector, styles ){
return styles.replace(/((?:\s|\n|\t)+)/gm, ' ').replace(/([^{]+)({[^}]+})/gm, function(_, selectors, styles ){
return selectors.split(',').map(function( selector ){
return parentSelector + ' ' + selector;
}).join(',') + styles;
});
}
function compile(){
var res = addParentSelector('.some-parent-selector', document.querySelector('#styles').value );
document.querySelector('#output').innerHTML = res;
}
/* ignore the css here */
textarea {
width: 100%;
height: 6em;
}
pre {
white-space:pre-wrap;
word-wrap:break-word;
}
button {
cursor: pointer;
display: inline-block;
text-align: center;
color: #fff;
line-height: 1;
padding: .6em .8em;
background: #009afd;
-webkit-transition: background 0.15s ease, color 0.15s ease;
-moz-transition: background 0.15s ease, color 0.15s ease;
-ms-transition: background 0.15s ease, color 0.15s ease;
-o-transition: background 0.15s ease, color 0.15s ease;
border: 1px solid #1777b7;
box-shadow: 0 1px 0 rgba(255,255,255,0.3) inset,0 1px 1px rgba(100,100,100,0.3);
border-radius: 3px;
}
button:hover {
color: #fff;
background: #0087de;
}
<textarea id='styles'>
.profile
{
line-height: 2;
padding: 1em;
font-family: sans-serif;
}
.profile__header { background: red; }
.profile__header-heading {
font-size: 2em;
padding: 0;
margin: 0;
}
.profile__header-heading small {
color: rgba(43,44,43,.7);
}
.profile__header-edit {
padding: .5em 2em;
border: .2em solid #3cf;
color: #fff;
background: #3cf;
text-decoration: none;
transition: .2s;
}
.profile__header-edit:hover {
color: #3cf;
background: #fff;
}
.profile__content p {
color: rgba(34,35,34,.7);
line-height: 2;
}
</textarea>
<button onclick="compile()">click me!</button>
<pre id="output"></pre>
edit: there was an issue in the Regex. I was using a [\s|\n|\t] group for space|newline|tab but it should have been a non capture group (?:\s|\n|\t).
This should be more complete. Also please be aware that Array.prototype.map() will fail in IE < 9.

Trigger opacity transition on mouse in and out

I want to trigger a opacity transition. If an element is hovered by the cursor, the cursor shall fade out, change its background-image and then fade in again. I wanted to achieve that by adding and removing a css class. It's not working, what is wrong?
js fiddle
HTML
<div class="wrapper">
<div class="cursor">
</div>
<div id="grey">
</div>
</div>
CSS
.wrapper {
width: 100%;
height: 100%;
background-color: lightgrey;
padding: 60px;
cursor: none;
}
#grey {
width: 100px;
height: 100px;
background: grey;
}
.cursor {
position: fixed;
width: 20px;
height: 20px;
pointer-events: none;
opacity: 0;
-webkit-transition: opacity .3s; /* Safari */
transition: opacity .3s;
}
.red {
background: red;
opacity: 1;
}
.green {
background: green;
opacity: 1;
}
JS
$('.wrapper').on('mousemove', function(e){
$('.cursor').css('left', e.clientX-10).css('top', e.clientY -10);
if ($.contains($('.wrapper')[0], e.target)){
$('.cursor').removeClass('green').addClass('red');
}else{
$('.cursor').removeClass('red').addClass('green');
}
});
DEMO HERE
Ok, here you go. You need to keep track of 2 things here which you already achieved partially and also wait for fadeOut to complete and add a callback for adding and removing respective class
Whether cursor has entered element
Whether cursor has left element
Below is how you could actually do it.
var entered=false;//global variables to show the position of cursor
var left=false;
$('.wrapper').on('mousemove', function(e){
$('.cursor').css('left', e.clientX-10).css('top', e.clientY -10);
if ($.contains($('.wrapper')[0], e.target)){
if(!entered)
{
//just to do it once and not on every mousemove you need to check here whether
//it has already entered and moving inside the element
entered=true;
left=false;//to check the vice versa operation
$('.cursor').fadeOut('fast',function(){
//callback function after fadeOut completes
$(this).removeClass('green').addClass('red');
}).fadeIn('fast');
}
}else{
if(!left)
{
left=true;
entered=false;
//same goes here too
$('.cursor').fadeOut('fast',function(){
$(this).removeClass('red').addClass('green');
}).fadeIn('fast');
}
}
});
you have to change background color , not opacity ( opacity is always 1 )
CSS
.cursor {
position: fixed;
width: 20px;
height: 20px;
pointer-events: none;
opacity: 0;
-webkit-transition: background-color .3s; /* Safari */
transition: background-color .3s ;
}
.red {
background-color: red;
opacity: 1;
}
.green {
background-color: green;
opacity: 1;
}
So you said your question is wrong, it is "no, I just made it easier for hier, in reality it is an background image" - so you transition between two background-images.
Here is how you do it:
You can not do it with CSS transition in ONE element/div
You will have to make two divs wich one background each
Increase the zIndex of the div you want to fade out in by one
Fade out div, while the new div stays at opacity: 1

How can a hover-over element still change other element styles when they're all in separate divs?

I understand that an element can change the style of associated elements upon hovering as long as they're within the same divs, but how can the same functionality be achieved when they're all in separate elements such as div, section, article, h1, etc.
I have set up a jsfiddle that consists of a version that works and a version that doesn't. As best, I would like to find out a way to achieve this through CSS only, but if it is an issue that only javascript can solve, that'll be okay.
I've been looking around StackOverflow but there doesn't seem to be an answer to what to do when the elements are within separate elements.
HTML
<h1>This version works fine...</h1>
... <span class="a1">fruits</span> and <span class="b1">vegetables</span>... <span class="a2">apple</span>, <span class="b2">asparagus</span>
<h1>...but how can I get this to work?</h1>
... <div class="div1"><span class="a1">fruits</span> and <span class="b1">vegetables</span></div>... <div class="div2"><span class="a2">apple</span>, <span class="b2">asparagus</span></div>
CSS
.a1, .b1 {
border:1px solid #333333;
padding: 0 1% 0 1%;
text-align: center;
-o-transition: color 0.2s ease-out;
-ms-transition: color 0.2s ease-out;
-moz-transition: color 0.2s ease-out;
-webkit-transition: color 0.2s ease-out;
transition: color 0.2s ease-out;
}
.a2, .b2 {
border:1px solid #dddddd;
padding: 0 1% 0 1%;
text-align: center;
-o-transition: color 0.2s ease-out;
-ms-transition: color 0.2s ease-out;
-moz-transition: color 0.2s ease-out;
-webkit-transition: color 0.2s ease-out;
transition: color 0.2s ease-out;
}
.a1:hover {
border:1px solid red;
color: white;
background-color: red;
}
.b1:hover {
border:1px solid green;
color: white;
background-color: green;
}
.a1:hover ~ .a2 {
border:1px solid red;
color: white;
background-color: red;
}
.b1:hover ~ .b2 {
border:1px solid green;
color: white;
background-color: green;
}
I've found out what the problem is.
Go to your code, fix or take off the lines below from the problematic part
</div>
<div class="div2">
Two problems
1 Closing DIV without a starting part
1 Opening DIV without closing part
See it working here
For jQuery: you can do something like
$(".a1").hover(function () {
$(".a2, .a1").css({"color":"white", "background-color":"red"});
});
See the jQuery example here
Note: If you have the DIV's there for a reason, try the jQuery method
CSS
.a1:hover, .a2.light { /* your css */ }
.b1:hover, .b2.light { /* your css */ }
JAVASCRIPT
var fruits = document.querySelectorAll('.div2 .a2'),
vegets = document.querySelectorAll('.div2 .b2'),
spanf = document.querySelector('.div1 .a1'),
spanv = document.querySelector('.div1 .b1');
spanf.addEventListener('mouseenter', function() {
[].forEach.call(fruits, function(el) {
el.classList.add('light');
});
});
spanf.addEventListener('mouseleave', function() {
[].forEach.call(fruits, function(el) {
el.classList.remove('light');
});
});
spanv.addEventListener('mouseenter', function() {
[].forEach.call(vegets, function(el) {
el.classList.add('light');
});
});
spanv.addEventListener('mouseleave', function() {
[].forEach.call(vegets, function(el) {
el.classList.remove('light');
});
});
DEMO
NOTE Safari doesn't support mouseenter / mouseleave. You can use mouseover / mouseout instead.
If you prefer a solution with jQUERY (it's less to write, but does the same under the hood):
var fruits = $('.div2 .a2'),
vegets = $('.div2 .b2');
$('.div1 .a1').hover(function() {fruits.toggleClass('light');});
$('.div1 .b1').hover(function() {vegets.toggleClass('light');});

Categories

Resources