Transition event listener doesn't execute - javascript

I'm working on transitions by using javascript. But i want to display element to none when the transition is end. I'm using addEventListener on element but function doesn't execute.
var fun;
var transitions = {
'transition':'transitionend',
'OTransition':'oTransitionEnd',
'MozTransition':'transitionend',
'WebkitTransition':'webkitTransitionEnd'
};
(function(){
var i=0,
containterget = document.querySelector('.container');
elementGet = document.querySelector('.Number');
fun = function(){
i++;
elementGet.innerHTML = i;
elementGet.style.transform = 'translateX('+(containterget.offsetWidth - 40 -35)+'px)';
elementGet.addEventListener(transitions,function(event){
console.log("Transition End Execute");
elementGet.style.display='none';
} );
};
})();
*{
margin:0;
padding:0;
box-sizing: border-box;
}
.container{
border:1px solid green;
max-width:85%;
margin: 2em auto 0;
}
button{
background-color:transparent;
padding: 15px;
margin:0;
color:#000;
border:2px solid #F44336;
text-align: center;
outline: 0;
transition: opacity 0.3s;
}
button:hover{
background-color:#F44336;
color: white;
opacity :.75;
}
button:hover{
cursor: pointer;
transition: opacity .4s;
}
span{
display: inline-block;
transition: transform 1.5s ease;
}
.Number{
font-size: 4em;
border:1px solid black;
/*transform: translateX(0);*/
}
.EndBoundry{
float: right;
font-size: 4em;
border:1px solid black;
}
.contain:after{
content: "";
display: table;
clear: both;
}
.btn{
text-align: center;
margin: 2em 0;
}
<div class="container contain">
<span class="Number">1</span>
<span class="EndBoundry">E</span>
</div>
<div class="btn">
<button onclick="fun()">Number Transition Click</button>
</div>

The following Snippet demonstrates the transitionend event. All details are commented in Snippet.
SNIPPET
// Reference the section#area and input#gone
var area = document.getElementById('area');
var chx = document.getElementById('gone');
// Register click event on #area call offON()
area.addEventListener('click', offON, false);
function offON(e) {
// Determine the clicked button
if (e.target !== e.currentTarget) {
var tgt = e.target;
// Switch clicked button classes .on and .off
tgt.classList.toggle('on');
tgt.classList.toggle('off');
}
// If the checkbox is checked call transEND()
if (chx.checked) {
transEND()
}
}
function transEND() {
// Register the transitionend event on #area
area.addEventListener("transitionend", function(e) {
// Determine which button was clicked
if (e.target !== e.currentTarget) {
var tgt = e.target;
// Clicked button will disappear after transition
tgt.style.display = 'none';
}
}, false);
}
/* All buttons will have the same
|| transition. This transition is
|| dependent upon another animatable
|| style to exist.
*/
/* This particular transition says:
|| ALL animatable styles have a
|| duration of 3 seconds,
|| with a timing function: ease,
|| and a delay of 300msec
*/
button {
width: 120px;
height: 40px;
transition: all 3s ease .3s
}
/* Classes .on and .off are "states"
|| to each #id the "states" have a
|| different meaning
*/
#fade.off {
opacity: 1;
}
#fade.on {
opacity: 0;
}
#move.off {
transform: translateY(0);
}
#move.on {
transform: translateY(200px);
}
#shrink.off {
transform: scale(1);
}
#shrink.on {
transform: scale(.3);
}
#gone {
width: 18px;
height: 18px;
}
p {
font-size: 12px;
}
<p>Click each button. Then click them again (the "FADER" is still there and clickable)</p>
<p>Now click the checkbox and push the buttons again. If you can't click the buttons back to original "state", then the event handler on transitionend was successful.</p>
<label for='gone'>Enable "transitionEND" </label>
<input id='gone' type='checkbox'>
<section id='area'>
<button id='fade' class='off'>FADER</button>
<button id='move' class='off'>MOVER</button>
<button id='shrink' class='off'>SHRINKER</button>
</section>

Use "transitionend" without prefixes
elementGet.addEventListener("transitionend", function(){});

You can listen to transitionend event on supported browsers.
I did some reshuffling of your codes and add an id tag to your button.
See snippet below
var fun;
var i = 0,
containterget = document.querySelector('.container');
elementGet = document.querySelector('.Number');
console.log(elementGet)
function execute(event) {
console.log("Transition End Execute");
alert("Transition End Execute");
elementGet.style.display = 'none';
}
fun = function() {
i++;
elementGet.innerHTML = i;
elementGet.style.transform = 'translateX(' + (containterget.offsetWidth - 40 - 35) + 'px)';
elementGet.addEventListener('transitionend', execute);
elementGet.addEventListener('webkitTransitionEnd', execute);
elementGet.addEventListener('mozTransitionEnd', execute);
elementGet.addEventListener('oTransitionEnd', execute);
};
document.getElementById("target").addEventListener("click", fun)
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.container {
border: 1px solid green;
max-width: 85%;
margin: 2em auto 0;
}
button {
background-color: transparent;
padding: 15px;
margin: 0;
color: #000;
border: 2px solid #F44336;
text-align: center;
outline: 0;
transition: opacity 0.3s;
}
button:hover {
background-color: #F44336;
color: white;
opacity: .75;
}
button:hover {
cursor: pointer;
transition: opacity .4s;
}
span {
display: inline-block;
transition: transform 1.5s ease;
}
.Number {
font-size: 4em;
border: 1px solid black;
/*transform: translateX(0);*/
}
.EndBoundry {
float: right;
font-size: 4em;
border: 1px solid black;
}
.contain:after {
content: "";
display: table;
clear: both;
}
.btn {
text-align: center;
margin: 2em 0;
}
<div class="container contain">
<span class="Number">1</span>
<span class="EndBoundry">E</span>
</div>
<div class="btn">
<script></script>
<button id="target">Number Transition Click</button>
</div>

Related

Template Literal Function not working as expected

I have a function that turns an array into modal window links as a template literal.
The code that creates the links works fine outside of the function
But once it gets rendered in the function it no longer works. I can't find any errors, but it does NOT work.
However, if I copy the HTML that the function renders and save that as actual HTML, that works fine on its own.
A good chunk of the JavaScript portion of the code is posted below. A full version is on Codepen.
There are two sections in the example on Codepen:
The first section has the code as it's rendered by the function.
The second section is copied from the Elements tab in Developer Tools and saved as actual HTML.
"use strict";
const modalBtns = document.querySelectorAll(".modal-button");
const modalWin = document.querySelector(".modal-window");
const closeBtn = document.querySelector(".close-modal");
const modal_iframe = document.getElementById("modal_iframe");
modalBtns.forEach((item) => {
item.addEventListener("click", function (e) {
let modal = e.currentTarget;
if (modal.dataset.target) {
let modalID = modal.dataset.target;
document.getElementById(modalID).style.display = "block";
}
if (modal.dataset.iframe) {
modal_iframe.src = modal.dataset.iframe;
document
.querySelector(".button-footer")
.addEventListener("click", function () {
window.open(modal.dataset.iframe, "_blank");
});
}
if (modal.dataset.header) {
document.querySelector(
".modal-header"
).innerHTML = `<h1>${modal.dataset.header}</h1>`;
}
if (modal.dataset.dimensions) {
document
.querySelector(".modal-window")
.setAttribute("style", modal.dataset.dimensions);
}
function loadIframe() {
let frame = document.getElementById("modal_window");
frame.style.height =
frame.contentWindow.document.body.scrollHeight + "px";
}
if (document.querySelector("#modal_window")) {
setTimeout(function () {
loadIframe;
}, 2000);
}
if (modal.dataset.reload && modal.dataset.reload === "1") {
document
.querySelector(".close-modal")
.addEventListener("click", function (e) {
console.log("parent.location.reload() pending...");
parent.location.reload();
});
}
/*======= All EventListeners Below Close Modal ================*/
closeBtn.addEventListener("click", function (e) {
document.querySelector(".modal-background").style.display = "none";
});
window.addEventListener("click", function (e) {
if (e.currentTarget === document.querySelector(".modal-background")) {
document.querySelector(".modal-background").style.display = "none";
}
});
document.body.addEventListener("keydown", (e) => {
if (e.key === "Escape") {
document.querySelector(".modal-background").style.display = "none";
}
});
});
});
const main = document.querySelector("main");
const modal_links = [
{
link: "https://notation.netcentrx.net/staff/",
header: "Musical Staff",
thb: "notation",
w_h: "min-width:60vw;max-width:600px;height:650px",
reload: 0
},
{
link: "https://wsl.netcentrx.net/",
header: "WSL Commands",
thb: "wsl",
w_h: "min-width:60vw;max-width:600px;height:650px",
reload: 0
}
];
let modalLink = "";
function createModalLinks(
link,
modalID,
header,
img,
w_h = "width:90vw;height:600px",
reload = "0"
) {
modalLink = `
<a href="javascript:void(0)" class="modal-button" onclick="console.log('onclick handler:${link}');" data-header="${header}" data-target="${modalID}" data-iframe="${link}" data-dimensions="${w_h};margin-top:20px" data-reload="${reload}">
<img src="https://resume.netcentrx.net/examples/${img}.jpg" title="${img}" width="50">
</a>
`;
return modalLink;
}
let theLinks = "";
modal_links.forEach((item) => {
theLinks += createModalLinks(
item.link,
"modal_window",
item.header,
item.thb,
item.w_h,
item.reload
);
});
main.innerHTML = theLinks;
My apologies in advance for it not being stripped down to just the bare minimum. But in order to replicate the problem, it required more code than it probably should have had. I've been reworking this for the better part of a day without any insight as to what the real problem is. I've been creating functions using template literals just like this for years now, usually with a high success rate. Whatever the problem is, I need to know so I can get past it. The only anomaly that I spotted is that–in the version on Codepen–the only thing that doesn't work in that version is once the modal is displayed clicking on the background does not dismiss the modal like it does elsewhere. If that's significant as to what the problem may be, I'm not sure what the connection is.
Usually when I take the time to painstakingly write everything out like this I typically either spot the problem or figure out an alternative solution so there's no need to actually post a question, but this does not appear to be one of those times. As always, your help is very much appreciated!
The issue appears to just be timing. Your code is executed in order, and the first part gets all of the modal buttons on the page and sets the appropriate event listeners. Then the second part of your code adds 2 modal buttons, which were not present earlier.
By simply wrapping the first part of your code in a function and calling it later (or swapping the order of those two parts of code), everything works as expected.
"use strict";
const _InitModal = () => {
const modalBtns = document.querySelectorAll(".modal-button");
const modalWin = document.querySelector(".modal-window");
const closeBtn = document.querySelector(".close-modal");
const modal_iframe = document.getElementById("modal_iframe");
modalBtns.forEach((item) => {
item.addEventListener("click", function (e) {
console.log("e.currentTarget = " + e.currentTarget);
let modal = e.currentTarget;
console.log("modal = " + modal);
if (modal.dataset.target) {
let modalID = modal.dataset.target;
console.log("modal.dataset.target = " + modal.dataset.target);
document.getElementById(modalID).style.display = "block";
}
if (modal.dataset.iframe) {
modal_iframe.src = modal.dataset.iframe;
document
.querySelector(".button-footer")
.addEventListener("click", function () {
window.open(modal.dataset.iframe, "_blank");
});
}
if (modal.dataset.header) {
document.querySelector(
".modal-header"
).innerHTML = `<h1>${modal.dataset.header}</h1>`;
console.log(`modal.dataset.header = ${modal.dataset.header}`);
}
if (modal.dataset.dimensions) {
document
.querySelector(".modal-window")
.setAttribute("style", modal.dataset.dimensions);
}
function loadIframe() {
let frame = document.getElementById("modal_window");
frame.style.height =
frame.contentWindow.document.body.scrollHeight + "px";
}
if (document.querySelector("#modal_window")) {
setTimeout(function () {
loadIframe;
}, 2000);
}
// e.preventDefault();
if (modal.dataset.reload && modal.dataset.reload === "1") {
document
.querySelector(".close-modal")
.addEventListener("click", function (e) {
console.log("parent.location.reload() pending...");
parent.location.reload();
});
}
/*======= All EventListeners Below Close Modal ================*/
closeBtn.addEventListener("click", function (e) {
document.querySelector(".modal-background").style.display = "none";
});
window.addEventListener("click", function (e) {
console.log("e.currentTarget = " + e.currentTarget);
if (e.currentTarget === document.querySelector(".modal-background")) {
document.querySelector(".modal-background").style.display = "none";
}
});
document.body.addEventListener("keydown", (e) => {
if (e.key === "Escape") {
console.log("e=" + e);
document.querySelector(".modal-background").style.display = "none";
}
});
});
});
}
const main = document.querySelector("main");
const modal_links = [
{
link: "https://notation.netcentrx.net/staff/",
header: "Musical Staff",
thb: "notation",
w_h: "min-width:60vw;max-width:600px;height:650px",
reload: 0
},
{
link: "https://wsl.netcentrx.net/",
header: "WSL Commands",
thb: "wsl",
w_h: "min-width:60vw;max-width:600px;height:650px",
reload: 0
}
];
function createModalLinks(
link,
modalID,
header,
img,
w_h = "width:90vw;height:600px",
reload = "0"
) {
let modalLink = "";
modalLink = `
<a href="javascript:void(0)" class="modal-button" onclick="console.log('onclick handler:${link}');" data-header="${header}" data-target="${modalID}" data-iframe="${link}" data-dimensions="${w_h};margin-top:20px" data-reload="${reload}">
<img src="https://resume.netcentrx.net/examples/${img}.jpg" title="${img}" width="50">
</a>`;
return modalLink;
}
let theLinks = "";
modal_links.forEach((item) => {
theLinks += createModalLinks(
item.link,
"modal_window",
item.header,
item.thb,
item.w_h,
item.reload
);
});
main.innerHTML = theLinks;
_InitModal();
.modal-background {
font-family: sans-serif;
position: fixed;
top: 0;
left: 0;
bottom: 0;
right: 0;
display: none;
overflow: auto;
background-color: rgba(0, 0, 0, 0.9);
z-index: 9999;
background: rgba(55, 55, 55, 0.6);
backdrop-filter: blur(10px);
-webkit-backdrop-filter: blur(10px);
}
.modal-window {
position: relative;
background-color: #ffffff;
width: 50%;
margin: 10% auto;
border-radius: 0.5rem;
padding: 0.75rem;
border: 1px groove #ccc;
/* box-shadow: 1px 1px 1px #999, 2px 2px 2px #000; */
}
.close-modal:hover,
.close-modal:focus {
color: rgba(255, 255, 255, 1);
cursor: pointer;
background: red;
transition: 1s;
text-shadow: 1px 1px 1px #999, 2px 2px 2px #000;
}
button.close-modal {
position: absolute;
top: -0.75rem;
right: -0.75rem;
padding: 0.05rem 0.75rem;
background: #999;
color: #ccc;
border-radius: 50%;
border: none;
outline: none;
-webkit-transition: all 0.5s cubic-bezier(0.23, 1, 0.32, 1);
transition: all 0.5s cubic-bezier(0.23, 1, 0.32, 1);
-webkit-animation-name: animatebottom;
-webkit-animation-duration: 1.5s;
animation-name: animatebottom;
animation-duration: 1.5s;
}
button.close-modal::before {
content: "\D7";
font-size: 2rem;
}
.modal-window {
display: flex;
flex-direction: column;
flex-wrap: nowrap;
-webkit-animation-name: animatetop;
-webkit-animation-duration: 0.5s;
animation-name: animatetop;
animation-duration: 0.5s;
}
.modal-header {
height: 30px;
text-align: center;
width: 100%;
background: #fff;
padding: 0.2rem;
}
.modal-header h1 {
font-size: 1.1rem;
}
.modal-footer {
height: 20px;
text-align: center;
width: 100%;
background: #fff;
padding: 0.2rem;
}
.modal-content {
background-color: #fff;
height: calc(100% - 70px);
border-radius: 0.5rem;
border: 0.1rem groove #ddd;
overflow: hidden;
}
.button-footer {
background: #fff;
border-radius: 0.5rem;
border: 1px outset #aaa;
padding: 0.2rem;
color: #999;
transition: 1s;
cursor: pointer;
}
.button-footer:hover {
background: #fdfdfd;
color: #555;
border: 1px inset #ddd;
text-shadow: 0.05rem 0.05rem 0.05rem #ccc, 0.055rem 0.055rem 0.055rem #999,
0.06rem 0.06rem 0.06rem #333;
transition: 1s;
}
.close-btn:hover {
color: white;
background: #f00;
cursor: pointer;
}
#modal_iframe {
width: 100%;
height: 100%;
}
button.modal-button {
border-radius: 0.5rem;
border: 0px solid #aaa;
padding: 0;
cursor: pointer;
}
.modal-button-img {
border-radius: 0.5rem;
border: 0.1rem groove #444;
cursor: pointer;
}
.sepia:hover {
filter: sepia(150%);
}
/*
.none {
display: none;
}
*/
#-webkit-keyframes animatetop {
from {
top: -300px;
opacity: 0;
}
to {
top: 0;
opacity: 1;
}
}
#keyframes animatetop {
from {
top: -300px;
opacity: 0;
}
to {
top: 0;
opacity: 1;
}
}
#-webkit-keyframes animatebottom {
from {
top: 0;
opacity: 1;
}
to {
bottom: -300px;
opacity: 0;
}
}
#keyframes animatebottom {
from {
top: 0;
opacity: 1;
}
to {
bottom: -300px;
opacity: 0;
}
}
.container {
border-radius: 0.5rem;
border: 1px solid #aaa;
max-width: 800px;
width: 500px;
margin: 0 auto;
text-align: center;
font-family: sans-serif;
}
main,
aside {
font-family: sans-serif;
max-width: 800px;
width: 500px;
margin: 0 auto;
text-align: center;
}
h2 {
text-align: center;
font-family: sans-serif;
font-weight: normal;
font-size: 1.2rem;
}
span {
font-size: 75%;
background: #ffff0055;
}
<div id="modal_window" class="modal-background">
<div class="modal-window">
<button class="close-modal" data-dismiss="modal"></button>
<div class="modal-header"></div>
<div class="modal-content">
<iframe src="#" id="modal_iframe" frameborder="0">If you'd have had a real browser, I wouldn't be boring you with this now...</iframe>
</div>
<div class="modal-footer"><button class="button-footer">Open In New Tab</button></div>
</div>
</div>
<div class="container">
<h2><code>main</code> Content Rendered By JavaScript</h2>
<main>
Main
</main>
<span>working now</span>
</div>

How to make an element move on the right after an input?

I am developing a project, and I made a custom input element. The problem is that whenever I try to add text, it shifts to the next line, so I was making it stop and shifting the position whenever input is added. I am making it go to the right whenever input is added(in my project, you can only add 1 text at a time). For the first few times, it works, but after 4 inputs, the space between the cursor(made by me/custom) and the closest text becomes more than it should be, for now, for a new input, the code adds 5px to the current margin, and the problem occurs, if I add 4px, the text moves too far. Is there any way that I can make my custom cursor move just as needed for it to look good.
Code(Note: I have code that is not used/is not needed, but I am scared that if I remove anything, something will go wrong, also you need to have a full page to see the cursor, else you can't see it, and the problem with it going below is something I have to solve once this problem is solved):
<!DOCTYPE html>
<html style="background-color:black; margin:0;padding:0;" lang="en-US">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<meta charset="utf-8"/>
<link rel="icon" href="icon.png"/>
<meta name="viewport" content="width=device-width,initial-scale=1.0"/>
<meta name="description" content="Description"/>
<title>MyTitle</title>
<style>
a{
color: inherit;
text-decoration: none;
}
*{
margin:0;
padding:0;
}
#heading{
color: white;
text-align: center;
font-size: 24px;
font-weight: 420 bold;
font-family: sans-serif;
text-shadow: 2px 2px red;
margin-right: 10px;
margin-top: 20px;
}
#description{
color: green;
text-align: center;
font-size: 19px;
font-weight: 69 bold;
font-family: serif;
text-shadow: 1px 1px white;
margin-right: 10px;
margin-top: 20px;
}
#cursor{
text-align: initial;
position: absolute;
left: 0;
font-weight: 35;
font-size: 25px;
color: #2E3D48;
-webkit-animation: 1s blink step-end infinite;
-moz-animation: 1s blink step-end infinite;
-ms-animation: 1s blink step-end infinite;
-o-animation: 1s blink step-end infinite;
animation: 1s blink step-end infinite;
}
#field{
color: white;
text-align: center;
font-size: 20px;
}
#fieldDiv{
background-color: #968786;
text-align: center;
width: 100%;
height: 28px;}
#keyframes "blink" {
from, to {
color: transparent;
}
50% {
color: black;
}
}
#-moz-keyframes blink {
from, to {
color: transparent;
}
50% {
color: black;
}
}
#-webkit-keyframes "blink" {
from, to {
color: transparent;
}
50% {
color: black;
}
}
#-ms-keyframes "blink" {
from, to {
color: transparent;
}
50% {
color: black;
}
}
#-o-keyframes "blink" {
from, to {
color: transparent;
}
50% {
color: black;
}
}
#cursorContainer{
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
#bton{
width: 20px;
height: 20px;
}
</style>
</head>
<body>
<h1 id="heading">
Heading
</h1>
<p id="description">Description</p>
<div id="fieldDiv">
<p id="field"></p><p id="cursorContainer" onclick="hideCursor()"><span id="cursor">|</span></p>
</div>
<br/>
<button id="bton" onclick="change();">
<!--Always add the script on the bottom of the BODY tag since it contains the script-->
<script type="text/javascript">
var marginNum = screen.width/2;
const screenWidth = screen.width;
function checkCtrlA(){
var ctrlPressed = false;
window.addEventListener("keydown", function(e){
if(e.keyCode == 17){
ctrlPressed = true;
}
});
if(ctrlPressed){
window.addEventListener("keydown", function(e){
if(e.keyCode == 65){
hideCursor();
}
})
}
}
window.onload = function(){
const cursor = document.getElementById("cursor");
const widthNeeded = innerWidth/2;
cursor.style.marginLeft = widthNeeded.toString() + "px";
cursor.style.cursor = "default";
};
const divToHide = document.getElementById("fieldDiv");
divToHide.onclick = hideCursor;
function printf(val){
console.log(val);
}
document.getElementById("fieldDiv").addEventListener('click', function(){
const element = document.getElementById("cursor");
element.style.visibility = "hidden";
});
document.getElementById("fieldDiv").addEventListener("mouseover", function(){
const element = document.getElementById("cursor");
element.style.visibility = "hidden";
});
document.getElementById("fieldDiv").addEventListener("mouseout", function(){
const element = document.getElementById("cursor");
element.style.visibility = "visible";
});
var currentText = document.getElementById("field").textContent;
function change(){
movePosCursor();
currentText = document.getElementById("field").textContent += "a";
document.getElementById("cursor").style.visibility = "visible";
}
function movePosCursor(){
const element = document.getElementById("cursor");
marginNum += 5;
var widthInPx = marginNum.toString() + "px";
element.style.marginLeft = widthInPx;
}
function hideCursor(){
const element = document.getElementById("cursor");
element.style.visibility = "hidden";
}
checkCtrlA();
</script>
</body>
</html>

How to properly animate a bar gliding?

I have two buttons, when a user clicks on them it gets underlined. However, I'd like the .underline to be animated/glide horizontally to the button that is being clicked on.
Demo: https://jsfiddle.net/ds1wr736/11/
As of right now, the .underline just appears and disapears when a button is clicked. How can I animate this to smoothly glide (x values changing) to the selected button without hacks and JQuery?
function switchTab(tab) {
if (tab === 1) {
document.getElementById("tab2").classList.add("underline");
document.getElementById("tab1").classList.remove("underline");
}
else if (tab === 2) {
document.getElementById("tab1").classList.add("underline");
document.getElementById("tab2").classList.remove("underline");
}
}
.bar {
background-color: gray;
padding: 20px;
}
.underline {
border-bottom: 5px solid red;
}
button {
width: 100px;
height: 50px;
background-color: white;
}
button:focus {
outline: none;
}
<div class="bar">
<button id='tab1' class="underline" onclick='switchTab(2)'>Tab 1</button>
<button id='tab2' onclick='switchTab(1)'>Tab 2</button>
</div>
Rather than animating a border I've created an additional element that reacts to the the click events. This allows us to track the position of the "underline" and scale and animate it between buttons when clicked.
This can be modified to accept hover events instead using mouseover instead of click.
let buttons = document.querySelectorAll('button');
buttons.forEach(button => {
button.addEventListener('mouseover', hoverboard); // Hover event
//button.addEventListener('click', hoverboard);
});
function hoverboard(e) {
const board = document.querySelector('.hoverboard');
// - 1 due to the border of the button
let width = this.offsetWidth - 1;
const firstChild = document.querySelector('.bar button:first-child');
const lastChild = document.querySelector('.bar button:last-child');
// - 19 due to padding being 20px on the left and removing 1 for the button's border
let left = this.offsetLeft - 19;
board.style.cssText = 'transform: translateX(' + left + 'px); width: ' + width + 'px;';
}
.bar {
position: relative;
background-color: gray;
padding: 20px;
}
.underline {
border-bottom: 5px solid red;
}
button {
width: 100px;
height: 50px;
background-color: white;
}
button:focus {
outline: none;
}
.hoverboard {
position: absolute;
width: 100px;
height: 3px;
background: red;
transition: transform .25s ease, width .25s ease;
}
<div class="bar">
<button id='tab1'>Tab 1</button>
<button id='tab2' style="width: 65px;">Tab 2</button>
<button>Tab 3</button>
<div class="hoverboard"></div>
</div>
Here ya go. Only the edited classes are here:
.underline:after {
border-bottom: 5px solid red;
animation-name: slideIn;
animation-duration: 1s;
width: 100%;
content: '';
position: absolute;
bottom: 0;
left: 0;
}
#keyframes slideIn {
from {width: 0;}
to {width: 100%;}
}
button{
position: relative;
width: 100px;
height: 50px;
background-color: white;
}
What I did is that I used the abstract after element on the buttons and positioned it absolute to it's relative button. And used css animation.

changing a `li` to input when button is clicked

I am wanting to change an <li> to a text input with the value of the <li> when an edit button is pressed
My solution for this is
let taskList = document.querySelector("#taskList");
const addTaskInput = document.querySelector("#addTaskInput");
const addTaskButton = document.querySelector("#addTaskButton");
const addTask = () => {
if (addTaskInput.value != " ") {
let taskItem = document.createElement("li");
taskItem.textContent = addTaskInput.value;
let checkBox = document.createElement("input");
checkBox.setAttribute("type", "checkBox");
let removeItem = document.createElement("button");
removeItem.setAttribute("class", "remove");
removeItem.textContent = "Delete";
let editItem = document.createElement("button");
editItem.textContent = "Edit"
editItem.setAttribute("class", "edit");
taskList.appendChild(taskItem);
taskItem.appendChild(checkBox);
taskItem.appendChild(removeItem);
taskItem.appendChild(editItem);
addTaskInput.value = " ";
};
}
addTaskButton.addEventListener("click", addTask);
// const checkbox = document.querySelector("input").addEventListener('change', () => {
// if (checkbox.checked == true) {
// console.log("check test");
// } else {
// console.log("not working");
// }
// });
addTaskInput.addEventListener("keydown", (event) => {
if (event.keyCode == 13) {
addTask();
}
});
taskList.addEventListener("click", (event) => {
if(event.target.tagName == "BUTTON") {
if (event.target.className == "remove") {
let taskItem = event.target.parentNode;
taskList = taskItem.parentNode;
taskList.removeChild(taskItem);
} else if (event.target.className == "edit") {
event.target.setAttribute("class", "done");
let taskItem = event.target.parentNode;
taskList = taskItem.parentNode;
let editMode = document.createElement("input");
editMode.setAttribute("type", "text");
editMode.setAttribute("value", taskItem.textContent);
taskList.replaceChild(taskItem, editMode);
}
}
});
html {
box-sizing: border-box;
}
*, *::after, *::before {
box-sizing: inherit;
}
* {
box-sizing: border-box;
font-family: sans-serif;
}
.wrapper {
width: 300px;
min-height: 300px;
border: 2px solid #000;
margin: 1rem auto;
padding: 1rem;
word-wrap: break-word;
position: relative;
}
ul {
padding-left: 0;
margin-left: 0;
}
ul li {
width: 100%;
padding: 1rem .25rem;
list-style: none;
border-bottom: 1px solid black;
}
ul li button {
width: 30%;
float: right;
border: none;
margin-right: .5rem;
background: none;
font-size: .75rem;
transition: background-color 0.5s ease;
-webkit-transition: color 0.5s ease;
color: #000;
}
ul li button:hover {
color: #777;
}
ul li input {
float: right;
}
#addTaskButton {
background: #fff;
border: .5px solid black;
margin: 1rem;
max-width: 100%;
height: 2rem;
border-radius: none;
transition: background-color 0.5s ease;
-webkit-transition: background-color 0.5s ease;
background-color: #fff;
}
#addTaskButton:hover {
background-color: #e7e7e7;
}
<body>
<div class="wrapper">
<ul id="taskList">
</ul>
<div id="add-task-area">
<input type="text" id="addTaskInput" value="">
<button id="addTaskButton">Add Task</button>
</div>
</div>
</body>
Essentially rebuilding the element and using the textContent as the value
(will add the changes to the <li> after solving this problem.
This solution doesn't work. Is this not how replaceChild works? Also there must be a less verbose way of implementing this?
JavaScript only please, also can you please explain any answers or feedback
https://codepen.io/hellojessicagraham/pen/Yxojqe
Reverse arguments of replaceChild. First argument is new node and second argument is old node which needs to be replaced.
taskList.replaceChild(editMode,taskItem)

How can I Disable a Clickable div right after onclick is initiated?

I couldnt find any answers on stack overflow to this specific question. I am trying to use pure javascript ONLY, so please no jquery answers.
So I posted all of my code as a general reference but my problem I believe lies in the javascript section. My question is, how can I make it so that my div "signup" is unclickable right AFTER it is clicked ONCE?
I tried putting a disable statement before frame and fadeOut are called inside the HideLogin() function. I also tried with css pointer-events. Nothing works and everytime I click SignUp, the animations repeat. Thank you in advance for the help.
function HideLogin() {
var login = document.getElementById("login");
var SignUpSheet = document.getElementById("SignUpSheet");
var titlecard = document.getElementById("titlecard");
var signup = document.getElementById("signup");
SignUpSheet.style.display = "block";
titlecard.style.display = "block";
frame(signup);
fadeOut(login);
/*fadeIn(document.getElementById("SignUpSheet"));
fadeIn(document.getElementById("titlecard")); */
}
function frame(signup) {
var pos = 125;
var id = setInterval(function() {
if (pos == 0) {
clearInterval(id);
} else {
pos--;
signup.style.top = pos + 'px';
}
}, 1);
}
function fadeOut(element) {
var op = 1; // initial opacity
var timer = setInterval(function() {
if (op <= 0.1) {
clearInterval(timer);
element.style.display = 'none';
}
element.style.opacity = op;
element.style.filter = 'alpha(opacity=' + op * 100 + ")";
op -= op * 0.1;
}, 20);
}
function fadeIn(element) {
var op = 0.1; // initial opacity
var timer = setInterval(function() {
if (op >= 1) {
clearInterval(timer);
}
element.style.opacity = op;
element.style.display = "block";
op += 0.1;
}, 20);
}
body,
html {
min-height: 100%;
}
body
/* Background handeling*/
{
color: white;
background: url(images/Hunter.jpg) center no-repeat;
background-size: cover;
background-color: #444;
}
/*------------------------------------------------------------- */
#logBox
/*Div that holds two links */
{
position: relative;
//border: 2px solid white;
height: 300px;
width: 300px;
margin-left: 70px;
margin-top: 50px;
}
#login
/* login link */
{
position: absolute;
cursor: pointer;
display: block;
//border: 2px solid white;
background: -webkit-linear-gradient(red, yellow);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
font-family: papyrus;
font-size: 70px;
color: red;
text-shadow: 2px 2px black;
transition: text-shadow 0.5s ease;
}
#login:hover {
background: -webkit-linear-gradient(white, black);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
text-shadow: 4px 4px black;
}
#signup
/* sign up link */
{
position: absolute;
cursor: pointer;
display: block;
//border: 2px solid white;
background: -webkit-linear-gradient(red, yellow);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
top: 125px;
font-family: papyrus;
font-size: 70px;
color: red;
text-shadow: 2px 2px black;
transition: text-shadow 0.5s ease;
}
#signup:hover {
background: -webkit-linear-gradient(white, black);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
text-shadow: 4px 4px black;
}
/*--------------------------------------------------------------- */
/* Div that holds two sheets */
#LogInSheet {
display: none;
}
#LoginTitle {}
#SignUpSheet {
display: none;
}
#SignUpTitle {}
/*--------------------------------------------------------------- */
#titlecard
/*title display */
{
position: absolute;
display: none;
bottom: 0px;
right: 50px;
//border: 2px solid white;
background: -webkit-linear-gradient(white, black);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
font-size: 45px;
color: gray;
text-align: center;
font-family: papyrus;
text-shadow: 2px 2px black;
}
<!doctype html>
<html>
<head>
<title>The Prime Legion</title>
<link rel="stylesheet" type="text/css" href="page1.css">
<script type="text/javascript" src="page1.js"></script>
</head>
<body>
<div id="logBox">
<div id="login" onclick="HideSignin()">
Log In
</div>
<div id="signup" onclick="HideLogin()">
Sign Up
</div>
</div>
<div id="LogInSheet">
<div id="LoginTitle">
<p>
<h4>Hello</h4>
</p>
</div>
</div>
<div id="SignUpSheet">
<div id="SignupTitle">
<p>
<h4>Welcome</h4>
</p>
</div>
</div>
<div id="titlecard">
<p>
<h1>The Prime Legion</h1>
</p>
</div>
</body>
</html>
Unless you have a particular need to use <div>s for your buttons, you could change the HTML to use <button> elements instead. That way you could disable it using the disabled attribute and it should prevent any further clicks without having to store and track any additional JavaScript variables.
<button id="signup" onclick="HideLogin()">Sign Up</button>
function HideLogin() {
document.getElementById("signup").disabled = true;
...
}
I would suggest the following:
define a global variable loginCliked=false
then in your HideLogin function:
HideLogin = function(){
if(!loginClicked){
loginClicked=true;
// Do everything else
}
}
So that with the first click it will set loginClicked to true. If you click the button for the second time it does nothing

Categories

Resources