Pausing Audio in Javascript - javascript

I'm trying to make a digital MPC with buttons that trigger different audio clips.
I got the buttons to function and play the audio when clicked once, however, I'm trying to make the audio pause when clicked again.
I've entered my entire code into this post incase anyone wanted to run it, however my issue is in the Javascript file with the "mousedown" function.
If anyone could offer insight I'd appreciate it.
$(document).ready(function() {
var padOne = new Audio('allstar.mp3');
$('.pad-1').mousedown(function() {
padOne.load()
padOne.play();
});
$(window).keydown(function(e) {
var code = e.keyCode;
var kc = String.fromCharCode(e.keyCode);
$("div[data-code='"+code+"']").addClass("active")
console.log(code);
switch(kc) {
case "R":
padOne.load();
padOne.play();
break;
}
});
$(window).keyup(function(e) {
var code = e.keyCode;
$("div[data-code='"+code+"']").removeClass("active");
});
});
#import 'https://fonts.googleapis.com/css?family=Oswald';
html, body {
background: #000000;
height: 100%;
width: 100%;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
overflow: hidden;
font-family: 'Oswald', sans-serif;
}
h1 {
color: #fff;
font-size: 5vw;
letter-spacing: 6px;
}
.pad {
width: 500px;
display: flex;
justify-content: space-between;
flex-wrap: wrap;
}
.box {
width: 100px;
height: 100px;
margin: 10px 0;
box-shadow: 0 8px 6px -6px black;
background-color: #444;
display: flex;
justify-content: center;
align-items: center;
font-size: 20px;
color: rgba(255, 255, 255, 0.4);
user-select: none;
&:hover {
background-color: lighten(#444, 10%);
cursor: pointer;
}
&:active {
background-color: darken(#444, 10%);
transform: scale(1.1);
transition: all .2s;
}
}
.active {
background-color: darken(#444, 10%);
transform: scale(1.1);
transition: all .2s;
}
.pad-1{
background-image: url(../images/shrek.jpg);
background-size:cover;
background-repeat: no-repeat;
background-position: center;
border: 2px solid #ffffff;
}
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Viral Remix</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<h1>VIRAL REMIXER</h1>
<div class="pad">
<div class="box pad-1" data-code="82">R</div>
</div>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js'></script>
<script src="js/scripts.js"></script>
</body>
</html>

I would just use a boolean flag to represent the playing state.
var playing = false;
$('.pad-1').mousedown(function() {
if(!playing) {
play();
} else {
pause();
}
});
function play() {
padOne.load();
padOne.play();
playing = true;
}
function pause() {
padOne.pause();
playing = false;
}

Related

why does this javascript code work differently? Is there any thing that I am missing?

i dont' get why my javascript code works differently despite it looks like same to me. I am a beginner and I tried to figure out what is wrong and I couldn't. In one method which I have commented the code works in a way it should work while in other it looks like the code is broken. It works in way it shouldn't and I couldn't figure out why it is happening.
let smallCups = document.querySelectorAll(".cup-small")
let liters = document.getElementById("liters")
let percentage = document.getElementById("percentage")
let remained = document.getElementById("remained")
// smallCups.forEach(function (cup, idx) {
// cup.addEventListener("click", function () {
// highLightCups(idx)
// })
// })
// function highLightCups(idx) {
// if (smallCups[idx].classList.contains("full")) {
// idx--
// }
// smallCups.forEach(function (cup, idx2) {
// if (idx2 <= idx) {
// cup.classList.add("full")
// } else {
// cup.classList.remove("full")
// }
// })
// }
smallCups.forEach(function(cup, idx) {
cup.addEventListener("click", function() {
if (smallCups[idx].classList.contains("full")) {
idx--
}
smallCups.forEach(function(cup, idx2) {
if (idx2 <= idx) {
cup.classList.add("full")
} else {
cup.classList.remove("full")
}
})
})
})
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
:root {
--border-color: #144fc6;
--fill-color: #6ab3f8;
}
html {
font-size: 62.5%;
/* 1rem = 10px */
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
body {
font-size: 1.6rem;
font-family: "Poppins", sans-serif;
background-color: #3494e4;
display: flex;
flex-direction: column;
align-items: center;
color: #fff;
}
h1 {
margin: 10px 0 0;
}
h3 {
font-weight: 400;
margin: 10px 0;
}
.cup {
background-color: #fff;
border: 4px solid var(--border-color);
color: var(--border-color);
border-radius: 0 0 40px 40px;
height: 330px;
width: 150px;
margin: 30px 0;
display: flex;
flex-direction: column;
overflow: hidden;
}
.cup.cup-small {
height: 95px;
width: 50px;
border-radius: 0 0 15px 15px;
background-color: rgba(255, 255, 255, 0.9);
cursor: pointer;
font-size: 14px;
align-items: center;
justify-content: center;
text-align: center;
margin: 5px;
transition: .3s ease;
}
.cups {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: center;
width: 280px;
}
.cup.cup-small.full {
background-color: var(--fill-color);
color: #fff;
}
.remained {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
text-align: center;
flex: 1;
transition: .3s ease;
}
.remained span {
font-size: 20px;
font-weight: 600;
}
.remained small {
font-size: 12px;
}
.percentage {
background-color: var(--fill-color);
display: flex;
align-items: center;
justify-content: center;
font-weight: bold;
font-size: 3rem;
height: 0;
transition: .3s ease;
}
.text {
text-align: center;
margin: 0 0 5px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght#100;200;300;400;500;600;700;800;900&display=swap" rel="stylesheet" />
<link rel="stylesheet" href="style.css" />
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<h2>drink water</h2>
<h3>goal : 2 liter</h3>
<div class="cup">
<div class="remained" id="remainded">
<span id="liters">1.5l</span>
<span>remained</span>
</div>
<div class="percentage" id="percentage">20%</div>
</div>
<p class="text">select how many glasses of water that you have drank</p>
<div class="cups">
<div class="cup cup-small">250ml</div>
<div class="cup cup-small">250ml</div>
<div class="cup cup-small">250ml</div>
<div class="cup cup-small">250ml</div>
<div class="cup cup-small">250ml</div>
<div class="cup cup-small">250ml</div>
<div class="cup cup-small">250ml</div>
<div class="cup cup-small">250ml</div>
</div>
<script src="https://kit.fontawesome.com/d48313b36e.js" crossorigin="anonymous"></script>
<script src="main.js"></script>
</body>
</html>
The problem is idx.
In the commented version idx is passed to the function and is passed by value. A local variable (also called idx) is created. Any changes to the value of idx are not persisted between clicks.
In your version the variable idx is captured in a closure by the event handler . Each time the click handler runs it gets the value of the captured variable idx which is being updated by the code. The next time the handler runs it uses the updated value of idx and not the original value.
To fix your version you will have to create a copy of idx e.g. let index = idx; and use the variable index inside the click handler to make sure the value of idx never changes!
let smallCups = document.querySelectorAll(".cup-small")
let liters = document.getElementById("liters")
let percentage = document.getElementById("percentage")
let remained = document.getElementById("remained")
smallCups.forEach(function(cup, idx) {
cup.addEventListener("click", function() {
// use original value of idx but do not update it!
let index = idx;
if (smallCups[index].classList.contains("full")) {
index--
}
smallCups.forEach(function(cup, idx2) {
if (idx2 <= index) {
cup.classList.add("full")
} else {
cup.classList.remove("full")
}
})
})
})
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
:root {
--border-color: #144fc6;
--fill-color: #6ab3f8;
}
html {
font-size: 62.5%;
/* 1rem = 10px */
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
body {
font-size: 1.6rem;
font-family: "Poppins", sans-serif;
background-color: #3494e4;
display: flex;
flex-direction: column;
align-items: center;
color: #fff;
}
h1 {
margin: 10px 0 0;
}
h3 {
font-weight: 400;
margin: 10px 0;
}
.cup {
background-color: #fff;
border: 4px solid var(--border-color);
color: var(--border-color);
border-radius: 0 0 40px 40px;
height: 330px;
width: 150px;
margin: 30px 0;
display: flex;
flex-direction: column;
overflow: hidden;
}
.cup.cup-small {
height: 95px;
width: 50px;
border-radius: 0 0 15px 15px;
background-color: rgba(255, 255, 255, 0.9);
cursor: pointer;
font-size: 14px;
align-items: center;
justify-content: center;
text-align: center;
margin: 5px;
transition: .3s ease;
}
.cups {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: center;
width: 280px;
}
.cup.cup-small.full {
background-color: var(--fill-color);
color: #fff;
}
.remained {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
text-align: center;
flex: 1;
transition: .3s ease;
}
.remained span {
font-size: 20px;
font-weight: 600;
}
.remained small {
font-size: 12px;
}
.percentage {
background-color: var(--fill-color);
display: flex;
align-items: center;
justify-content: center;
font-weight: bold;
font-size: 3rem;
height: 0;
transition: .3s ease;
}
.text {
text-align: center;
margin: 0 0 5px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght#100;200;300;400;500;600;700;800;900&display=swap" rel="stylesheet" />
<link rel="stylesheet" href="style.css" />
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<h2>drink water</h2>
<h3>goal : 2 liter</h3>
<div class="cup">
<div class="remained" id="remainded">
<span id="liters">1.5l</span>
<span>remained</span>
</div>
<div class="percentage" id="percentage">20%</div>
</div>
<p class="text">select how many glasses of water that you have drank</p>
<div class="cups">
<div class="cup cup-small">250ml</div>
<div class="cup cup-small">250ml</div>
<div class="cup cup-small">250ml</div>
<div class="cup cup-small">250ml</div>
<div class="cup cup-small">250ml</div>
<div class="cup cup-small">250ml</div>
<div class="cup cup-small">250ml</div>
<div class="cup cup-small">250ml</div>
</div>
<script src="https://kit.fontawesome.com/d48313b36e.js" crossorigin="anonymous"></script>
<script src="main.js"></script>
</body>
</html>

How can i remove the user input added paragraph automatically after 2 seconds in javascript?

i just learned how to create a to-do list in java script and as a personal project i wanted to use the information i learned in to-do app making by creating a tell your secret website which like the
const mytext = document.getElementById('mytext');
const btn = document.getElementById('btn');
const items = document.getElementById('items');
btn.addEventListener('click', function(e){
e.preventDefault();
const paragraph = document.createElement('p');
paragraph.classList.add("item");
paragraph.innerText = mytext.value;
items.appendChild(paragraph);
mytext.value = '';
});
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
background-color: rgb(231, 237, 241);
}
main {
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
margin-top: 10%;
font-family: "Source Sans Pro", sans-serif;
}
h2 {
color: rgb(71, 80, 102);
font-size: 40px;
margin-bottom: 30px;
}
.myform {
display: flex;
justify-content: center;
align-items: center;
}
#btn {
margin-left: 10px;
width: 40px;
height: 100px;
white-space: pre-line;
text-align: center;
font-size: 15px;
font-weight: 600;
border: none;
border-radius: 10px;
cursor: pointer;
box-shadow: 2px 2px rgb(184, 182, 182);
color: rgb(35, 70, 136);
}
#btn:active {
color: rgb(48, 95, 182);
box-shadow: 0 0 2px grey;
}
#mytext {
background-color: aliceblue;
border-radius: 10px;
border: none;
padding: 7px;
box-shadow: 1px 1px rgb(200, 207, 212);
outline: none;
}
.items {
border-radius: 5px;
font-family: cursive;
color: rgb(61, 61, 60);
width: 400px;
display: flex;
justify-content: center;
margin-top: 10px;
padding: 5px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=MedievalSharp&display=swap" rel="stylesheet">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Source+Sans+Pro:wght#200;300;400;600;700;900&display=swap" rel="stylesheet">
<link rel="stylesheet" href="./styles.css">
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<main>
<h2>Write Your Secret</h2>
<div class="container">
<form class="myform" action="">
<textarea name="text" id="mytext" cols="30" rows="10" placeholder="Write Whatever You Wish"></textarea>
<button id="btn">S
h
a
r
e</button>
</form>
<div class="items" id="items"></div>
</div>
</main>
<script src="./app.js"></script>
</body>
</html>
to-do app user writes something in the box (his/her secret) and the secret is displayed on the screen but
this is what i need:
i need the displayed paragraph to be removed automatically after 2 second like the secret vanishes 2 second after you write it.even better if it vanishes slowly like the ink vanishes in harry potter movie in tom riddle diary but that's not important i just want to remove the secret after 2 seconds first and then worry about the style that it vanishes.
With the simple addition of this code:
setTimeout(() => paragraph.classList.add("hidden"), 2000)
Which adds the class "hidden" after 2 seconds it will do what you want. You could make class hidden do anything, such as just set the visibility to hidden but you can also do transition effects like the one you deswcribe:
.hidden {
visibility: hidden;
opacity: 0;
transition: visibility 0s 2s, opacity 2s linear;
}
If using a transition like above you can also add this line to remove the element when the transition completes
paragraph.addEventListener('transitionend',() => paragraph.remove())
Live example below
const mytext = document.getElementById('mytext');
const btn = document.getElementById('btn');
const items = document.getElementById('items');
btn.addEventListener('click', function(e){
e.preventDefault();
const paragraph = document.createElement('p');
paragraph.classList.add("item");
paragraph.innerText = mytext.value;
items.appendChild(paragraph);
mytext.value = '';
paragraph.addEventListener('transitionend',() => paragraph.remove())
setTimeout(() => paragraph.classList.add("hidden"), 2000)
});
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
background-color: rgb(231, 237, 241);
}
main {
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
margin-top: 10%;
font-family: "Source Sans Pro", sans-serif;
}
h2 {
color: rgb(71, 80, 102);
font-size: 40px;
margin-bottom: 30px;
}
.myform {
display: flex;
justify-content: center;
align-items: center;
}
#btn {
margin-left: 10px;
width: 40px;
height: 100px;
white-space: pre-line;
text-align: center;
font-size: 15px;
font-weight: 600;
border: none;
border-radius: 10px;
cursor: pointer;
box-shadow: 2px 2px rgb(184, 182, 182);
color: rgb(35, 70, 136);
}
#btn:active {
color: rgb(48, 95, 182);
box-shadow: 0 0 2px grey;
}
#mytext {
background-color: aliceblue;
border-radius: 10px;
border: none;
padding: 7px;
box-shadow: 1px 1px rgb(200, 207, 212);
outline: none;
}
.items {
border-radius: 5px;
font-family: cursive;
color: rgb(61, 61, 60);
width: 400px;
display: flex;
justify-content: center;
margin-top: 10px;
padding: 5px;
}
.hidden {
visibility: hidden;
opacity: 0;
transition: visibility 0s 2s, opacity 2s linear;
}
<main>
<h2>Write Your Secret</h2>
<div class="container">
<form class="myform" action="">
<textarea name="text" id="mytext" cols="30" rows="10" placeholder="Write Whatever You Wish"></textarea>
<button id="btn">S
h
a
r
e</button>
</form>
<div class="items" id="items"></div>
</div>
</main>
const btn = document.getElementById('btn');
const items = document.getElementById('items');
const clearInput = () => {
setInterval(function(){mytext.value = ''; }, 2000);
}
btn.addEventListener('click', function(e){
e.preventDefault();
const paragraph = document.createElement('p');
paragraph.classList.add("item");
paragraph.innerText = mytext.value;
items.appendChild(paragraph);
mytext.value = '';
});
clearInput()

Toggle button onClick method doesn't work [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 2 years ago.
I don't understand why this code doesn't work.
It works on an online platform such as jsfiddle but it doesn't work when I try it on VS Code live server.
This code provide that responsive header. If the size of page less than 1210 pixels navbar not seems. navbar seems if you click the button. Sorry for my english.
https://jsfiddle.net/1n8zv5xL/1/
HTML
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="layout.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="contact.js"></script>
<script src="preparePage.js"></script>
</head>
<body>
<a id="infoButton" class="infoButton" href="info.html"></a>
<a id="bodyButton" class="bodyButton" href="body.html"></a>
<a id="enterButton" class="enterButton" onclick="preparePage(); return false;"></a>
<a id="leaveButton" class="leaveButton" href="leave.html"></a>
<a id="contactButton" class="contactButton" onclick="contact(); return false;"></a>
</body>
<footer>
</footer>
</html>
CSS
#import url("https://db.onlinewebfonts.com/c/b2932945dbc71a0a2a4c03dd305cfe3a?family=Bauhaus");
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
header {
background-color:white;
justify-content: space-between;
display: flex;
align-items: center;
padding: 25px 15%;
height: 100px;
}
li,a,button {
font-family: "Montserrat", sans-serif;
font-weight: 500;
font-size: 16px;
color: black;
text-decoration: none;
}
header h1 {
font-family: "Bauhaus";
color:rgba(0, 136, 169, 1);
font-size: 45px;
}
button {
padding: 9px 25px;
background-color: rgba(0, 136, 169, 1);
border: none;
border-radius: 50px;
cursor: pointer;
transition: all 0.3s ease 0s;
}
button:hover {
background-color: rgba(0, 136, 169, 0.8);
}
html{
overflow-y: scroll;
}
.navbar-links {
list-style: none;
}
.navbar-links li {
display: inline-block;
padding: 0px 20px;
}
.navbar-links li a {
transition: all 0.3s ease 0s;
}
.navbar-links li a:hover {
color: rgba(0, 136, 169, 1);
}
.logo {
width: 500px;
display: flex;
flex-direction: initial;
align-items: center;
justify-content: space-around;
}
.toggle-button {
top: .75rem;
right: 1rem;
display: none;
flex-direction: column;
justify-content: space-between;
width: 30px;
height: 21px;
}
.toggle-button .bar {
height: 3px;
width: 100%;
background-color: black;
border-radius: 10px;
}
#media screen and (max-width:1210px) {
header {
flex-direction: column;
}
.navbar-links {
display: flex;
flex-direction: column;
}
.toggle-button {
display: flex;
}
.navbar-links.active {
display: none;
}
}
JAVASCRİPT
const toggleButton = document.getElementsByClassName('toggle-button')[0]
const navbarLinks = document.getElementsByClassName('navbar-links')[0]
toggleButton.addEventListener('click', () => {
navbarLinks.classList.toggle('active')
})
The problem is with the head.
You are including the scripts in head so it will be loaded prior to the document. So, inorder for you to access dom nodes you should listen for the ready event in jquery - or you can move the scripts to the end of the body
Eg:
$(function() {
const toggleButton = document.getElementsByClassName('toggle-button')[0]
const navbarLinks = document.getElementsByClassName('navbar-links')[0]
toggleButton.addEventListener('click', () => {
navbarLinks.classList.toggle('active')
})
})
OR
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="layout.css">
</head>
<body>
<a id="infoButton" class="infoButton" href="info.html"></a>
<a id="bodyButton" class="bodyButton" href="body.html"></a>
<a id="enterButton" class="enterButton" onclick="preparePage(); return false;"></a>
<a id="leaveButton" class="leaveButton" href="leave.html"></a>
<a id="contactButton" class="contactButton" onclick="contact(); return false;"></a>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="contact.js"></script>
<script src="preparePage.js"></script>
</body>
<footer>
</footer>
</html>
That should do the trick.

js for custom select works in codepen and jsfiddle but not in browser?

I'm working on a custom select element, the code runs as expected in codepen and jsfiddle, but won't drop down if I run it in browser. I've never implemented js in a web project before so I feel like I'm missing something fairly simple.
here's the link to the codepen: https://codepen.io/kylegendy/pen/xxwYrPr
and here's the code I put in...:
script.js
for (const dropdown of document.querySelectorAll(".custom-select-wrapper")) {
dropdown.addEventListener('click', function() {
this.querySelector('.custom-select').classList.toggle('open');
})
}
for (const option of document.querySelectorAll(".custom-option")) {
option.addEventListener('click', function() {
if (!this.classList.contains('selected')) {
this.parentNode.querySelector('.custom-option.selected').classList.remove('selected');
this.classList.add('selected');
this.closest('.custom-select').querySelector('.custom-select__trigger span').textContent = this.textContent;
}
})
}
window.addEventListener('click', function(e) {
for (const select of document.querySelectorAll('.custom-select')) {
if (!select.contains(e.target)) {
select.classList.remove('open');
}
}
});
function selectOption(index) {
var optionOnIdx = document.querySelector('.custom-option:nth-child(' + index + ')');
var optionSelected = document.querySelector('.custom-option.selected');
if (optionOnIdx !== optionSelected) {
optionSelected.parentNode.querySelector('.custom-option.selected').classList.remove('selected');
optionOnIdx.classList.add('selected');
optionOnIdx.closest('.custom-select').querySelector('.custom-select__trigger span').textContent = optionOnIdx.textContent;
}
}
document.querySelector('button').addEventListener("click", function() {
selectOption(2);
});
template.css
*,
*:after,
*:before {
box-sizing: border-box;
}
.container .custom-select-wrapper {
display: flex;
text-align: center;
/* centeres the text horizontally */
width: 300px;
border-width: thick;
border-color: blue;
border-style: solid;
}
custom-select-wrapper>div {
display: inline-block;
position: relative;
max-width: 50%;
}
.container .selectName {
display: flex;
justify-content: center;
align-items: center;
position: relative;
user-select: none;
border-width: thick;
border-color: red;
border-style: none solid none none;
background-color: rgba(228, 228, 228, 0.39);
}
.custom-select-wrapper {
position: relative;
user-select: none;
}
.custom-select {
display: flex;
flex-direction: column;
border-width: 0;
}
.custom-select-wrapper>div {
display: inline-block;
/* blocks just line up without floats */
position: relative;
/* sets positioning context for 2nd level menu */
width: 50%;
height: 60px;
}
.custom-select__trigger {
position: relative;
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 22px;
color: rgba(83, 83, 83, 1);
line-height: 60px;
background-color: rgba(228, 228, 228, 0.39);
cursor: pointer;
border-width: 0;
}
.custom-options {
position: absolute;
display: block;
top: 100%;
left: 0;
right: 0;
border: none;
background: white;
transition: all 0.5s;
opacity: 0;
visibility: hidden;
}
.custom-select.open .custom-options {
opacity: 1;
visibility: visible;
}
.custom-option {
position: relative;
display: block;
padding: 0 22px 0 22px;
color: rgba(83, 83, 83, 1);
line-height: 60px;
cursor: pointer;
}
.custom-option:hover {
cursor: pointer;
background-color: rgba(228, 228, 228, 0.39);
}
.custom-option.selected {
color: white;
background-color: rgb(149, 189, 204);
}
.arrow {
position: relative;
height: 15px;
width: 15px;
}
.arrow::before,
.arrow::after {
content: "";
position: absolute;
bottom: 0px;
width: 0.15rem;
height: 100%;
transition: all 0.5s;
}
.arrow::before {
left: -5px;
transform: rotate(45deg);
background-color: #394a6d;
}
.arrow::after {
left: 5px;
transform: rotate(-45deg);
background-color: #394a6d;
}
.open .arrow::before {
left: -5px;
transform: rotate(-45deg);
}
.open .arrow::after {
left: 5px;
transform: rotate(45deg);
}
template.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>the wall</title>
<link href="template.css" rel="stylesheet" type="text/css">
<script src="script.js" type="text/javascript"></script>
</head>
<body>
<div class="container">
<div class="custom-select-wrapper">
<div class="selectName"><span>Type</span></div>
<div class="custom-select">
<div class="custom-select__trigger"><span>Tesla</span>
<div class="arrow"></div>
</div>
<div class="custom-options">
<span class="custom-option selected" data-value="tesla">Tesla</span>
<span class="custom-option" data-value="volvo">Volvo</span>
<span class="custom-option" data-value="mercedes">Mercedes</span>
</div>
</div>
</div>
</div>
</body>
</html>
edit: I deleted the segment of js code starting at line 38 in jsfiddle and codepen and the dropdown worked the same, the way it’s supposed to, but when I got rid of it in the files to run on browser, although the error disappears, the dropdown still doesn’t work.
Put your script in a function like below
function Test(){
for (const dropdown of document.querySelectorAll(".custom-select-wrapper")) {
dropdown.addEventListener('click', function () {
this.querySelector('.custom-select').classList.toggle('open');
})
}
for (const option of document.querySelectorAll(".custom-option")) {
option.addEventListener('click', function () {
if (!this.classList.contains('selected')) {
this.parentNode.querySelector('.custom-option.selected').classList.remove('selected');
this.classList.add('selected');
this.closest('.custom-select').querySelector('.custom-select__trigger span').textContent = this.textContent;
}
})
}
window.addEventListener('click', function (e) {
for (const select of document.querySelectorAll('.custom-select')) {
if (!select.contains(e.target)) {
select.classList.remove('open');
}
}
});
function selectOption(index) {
var optionOnIdx = document.querySelector('.custom-option:nth-child('+index+')');
var optionSelected = document.querySelector('.custom-option.selected');
if (optionOnIdx !== optionSelected) {
optionSelected.parentNode.querySelector('.custom-option.selected').classList.remove('selected');
optionOnIdx.classList.add('selected');
optionOnIdx.closest('.custom-select').querySelector('.custom-select__trigger span').textContent = optionOnIdx.textContent;
}
}
}
and call this function from your HTML page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>the wall</title>
<link href="template.css" rel="stylesheet" type="text/css">
<script src="script.js" type="text/javascript"></script>
</head>
<body>
<div class="container">
<div class="custom-select-wrapper">
<div class="selectName"><span>Type</span></div>
<div class="custom-select">
<div class="custom-select__trigger"><span>Tesla</span>
<div class="arrow"></div>
</div>
<div class="custom-options">
<span class="custom-option selected" data-value="tesla">Tesla</span>
<span class="custom-option" data-value="volvo">Volvo</span>
<span class="custom-option" data-value="mercedes">Mercedes</span>
</div>
</div>
</div>
</div>
<script>
Test();
</script>
</body>
</html>
and remove the following piece of code from your script.js page
document.querySelector('button').addEventListener("click", function() {
selectOption(2);
});

how to replace an image with another onclick

I have these characteristics of these two images
#image1{
position:absolute;
left:29%;
top:40%;
background-image: url("../imgdrag/activity1.png");
width:63px;
height:38px;
}
#image2{
position:absolute;
left:29%;
top:40%;
background-image: url("../imgdrag/activity1red.png");
width:63px;
height:38px;
}
How can I replace the image1 with the image2 when I click on a button using a function
Example of switching state with jQuery
$('.replace').click(function(){
$('.image-holder').toggleClass('active');
})
#image1{
position:absolute;
left:29%;
top:40%;
background-image: url("../imgdrag/activity1.png");
width:63px;
height:38px;
z-index: 2;
background-color: blue;
}
#image2{
position:absolute;
left:29%;
top:40%;
background-image: url("../imgdrag/activity1red.png");
width:63px;
height:38px;
z-index: 1;
background-color: red;
}
.image-holder {
position: relative;
}
.image-holder.active #image2{
z-index: 3;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="replace">Replace</button>
<div class="image-holder">
<div id="image1"></div>
<div id="image2"></div>
</div>
What I would recommend is to change your css to
#image1 {
position:absolute;
left:29%;
top:40%;
background-image: url("../imgdrag/activity1.png");
width:63px;
height:38px;
}
#image1.active {
background-image: url("../imgdrag/activity1red.png");
}
then if you are using jquery just add the new 'active' class, and remember to check first if it already has it.
$('button').on('click', function(e) {
var img = $('#image1');
if (!img.hasClass('active')) {
img.addClass('active');
}
});
// this with jQuery
$("#button").click(function() {
$('#image1').attr('id', '#image2');
});
or
function change(){
document.getElementById('#image1').setAttribute('id', '#image2');
}
You can use addEventListner Like the below code:
// Tempory you can use an hard coded to
const replaceImageSrc = "https://images.unsplash.com/photo-1503023345310-bd7c1de61c7d?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8aHVtYW58ZW58MHx8MHx8&w=1000&q=80"
// Replace Image
const image = document.getElementById('image');
// Replace button
const replaceBtn = document.getElementById('replace-img-btn');
const imagesReplace = (img) =>{
if(img != ""){
image.src=`${img}`
}else{
image.src=""
}
}
replaceBtn.addEventListener('click', ()=>{
imagesReplace(replaceImageSrc)
})
/* Fonts */
#import url("https://fonts.googleapis.com/css2?family=Nunito:wght#300&display=swap");
:root {
--primary-color: rgb(26, 26, 26);
--secondary-color: rgb(245, 245, 245);
--font-family: Nunito, sans-serif;
--box-shadow: rgb(0, 0, 0) 1px 1px 3px 0px inset, rgba(48, 48, 48, 0.5) -1px -1px 3px 1px inset;;
--all-transition: transform ease-in-out 0.3s 0s;
}
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
body{
font-family: var(--font-family);
}
.main-content{
width: 100vw;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
.container{
width: 550px;
height: 250px;
display: flex;
justify-content: space-between;
align-items: center;
flex-direction: column;
border-radius: 10px;
background-color: var(--primary-color);
}
.img-container{
width: 100%;
padding: 5px;
display: flex;
justify-content: center;
align-items: center;
margin-top: 10px;
}
.img-container>img{
width: 100px;
border-radius: 10px;
}
.container>button{
width: 200px;
height: 35px;
border-radius: 5px;
border: none;
font-weight: bold;
margin-bottom: 15px;
box-shadow: var(--box-shadow);
background-color: var(--primary-color);
color: var(--secondary-color);
cursor: pointer;
transition: var(--all-transition);
}
/* Animation */
.container>button:hover{
transform: scale(1.08);
}
.container>button:active{
background-color: var(--secondary-color);
color: var(--primary-color);
box-shadow: none;
border: 1px solid var(--secondary-color);
}
<!doctype HTML>
<html>
<head>
<title>codedamn HTML Playground</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/style.css" />
</head>
<body>
<div class="main-content">
<div class="container">
<div class="img-container">
<img src="https://images.unsplash.com/photo-1541963463532-d68292c34b19?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxleHBsb3JlLWZlZWR8Mnx8fGVufDB8fHx8&w=1000&q=80" id="image" alt="">
</div>
<button type="button" name="replace-img-btn" id="replace-img-btn">Replace Image</button>
</div>
</div>
<script src="/script.js"></script>
</body>
</html>

Categories

Resources