select drop down css
display: block;
height: 60px;
margin-left: 10%;
margin-right: 10%;
margin-top: 10px;
min-height: 60px;
text-align: center;
option text is centered in firefox browser,but not in safari,
Is there any solution to get text aligned in center in safari browser?
Add padding and remove the height. For example here is an update of the code you have supplied:
display: block;
margin-left: 10%;
margin-right: 10%;
margin-top: 10px;
padding-top: 10px;
padding-right: 20px;
padding-bottom: 10px;
padding-left: 20px;
UPDATE
Unfortunately padding may not work in Safari (iPhone). In this case try using text indent instead of padding. And add the text indent of the width of your drop down menu. Please see an update of the code you provided:
display: block;
height: 60px;
margin-left: 10%;
margin-right: 10%;
margin-top: 10px;
min-height: 60px;
width: 220px; /* width of 200px plus the 20px for the text indent */
text-indent: 20px;
You could use top and bottom padding and remove height to align the text in the middle.
padding: 30px;
If you are desperate, use this one codepen Crossbrowser Select
$(document).ready(() => {
$('.crossbrowser-select').on('click', crossbrowserSelectOnClickEvent);
$('.crossbrowser-select').on('mouseWheelDown', crossbrowserSelectOnMouseWheelDownEvent);
$('.crossbrowser-select').on('mouseWheelUp', crossbrowserSelectOnMouseWheelUpEvent());
$('.crossbrowser-select > .option').on('click', crossbrowserSelectItemOnClickEvent);
$('.crossbrowser-select').focusout('click', crossbrowserSelectOnFocusOutEvent);
//Firefox
$('.crossbrowser-select').bind('DOMMouseScroll', function(e){
if (e.originalEvent.detail > 0) {
//scroll down
chooseNextItem($(this));
} else {
//scroll up
choosePreviousItem($(this));
}
//prevent page fom scrolling
return false;
});
//IE, Opera, Safari
$('.crossbrowser-select').bind('mousewheel', function(e){
if(e.originalEvent.wheelDelta < 0) {
//scroll down
chooseNextItem($(this));
}else {
//scroll up
choosePreviousItem($(this));
}
//prevent page fom scrolling
return false;
});
$('.crossbrowser-select').keyup(function(event) {
if (event.keyCode === 32) { //Enter
event.preventDefault();
toggleSelect($(this));
}
if (event.keyCode === 38) { //Up
event.preventDefault();
choosePreviousItem($(this));
}
if (event.keyCode === 40) { //Down
event.preventDefault();
chooseNextItem($(this));
}
});
});
/* METHODS ************************************************************************************************************/
function toggleSelect(select) {
if (select.hasClass('expanded')) {
select.toggleClass('expanded');
select.children('.option').removeClass('shown');
} else {
select.toggleClass('expanded');
select.children('.option').each(function () {
const item = $(this);
const select = item.parent();
if (item.attr('value') !== select.attr('value')) {
item.toggleClass('shown');
}
});
}
}
function collapseSelect(select) {
select.removeClass('expanded');
select.children('.option').each(function () {
$(this).removeClass('shown');
});
}
function chooseNextItem(select) {
collapseSelect(select);
if (select.attr('value') !== '') {
const selectedItem = select.children('div[value=\'' + select.attr('value') + '\']');
const nextSibling = selectedItem.next('.option');
if (nextSibling) {
select.attr('value', nextSibling.attr('value'));
select.children('.visual-option').html(nextSibling.html());
}
} else {
selectFirstItem(select);
}
}
function choosePreviousItem(select) {
collapseSelect(select);
if (select.attr('value') !== '') {
const selectedItem = select.children('div[value=\'' + select.attr('value') + '\']');
const prevSibling = selectedItem.prev('.option');
if (prevSibling) {
select.attr('value', prevSibling.attr('value'));
select.children('.visual-option').html(prevSibling.html());
}
} else {
selectFirstItem(select);
}
}
function chooseItem(item) {
const select = item.parent('.crossbrowser-select');
select.children('.visual-option').html(item.html());
select.attr('value', (item.attr('value')));
}
function selectFirstItem(select) {
const firstItem = select.children('.option').first();
select.attr('value', firstItem.attr('value'));
select.children('.visual-option').html(firstItem.html());
}
/* Events *************************************************************************************************************/
function crossbrowserSelectOnClickEvent() {
toggleSelect($(this));
}
function crossbrowserSelectItemOnClickEvent() {
chooseItem($(this));
}
function crossbrowserSelectOnMouseWheelDownEvent() {
chooseNextItem($(this));
}
function crossbrowserSelectOnMouseWheelUpEvent() {
choosePreviousItem($(this));
}
function crossbrowserSelectOnFocusOutEvent() {
collapseSelect($(this));
}
.crossbrowser-select {
text-align: center;
cursor: pointer;
border: 1px transparent solid;
border-bottom: 1px solid #70ccd9;
border-radius: 10px;
}
.crossbrowser-select.expanded {
color: #70ccd9;
border-top: 1px solid #70ccd9;
}
.crossbrowser-select:hover,
.crossbrowser-select:focus,
.crossbrowser-select:active {
outline: none;
border: 1px solid white;
background-color: transparent;
}
.crossbrowser-select > .option {
display: none;
color: white;
}
.crossbrowser-select > .option.shown {
display: block;
}
<html>
<head>
<title></title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>
<body style="background-color: black; color: white; padding: 50px">
<div class="col-4 text-center">
<div style="margin-bottom: 20px">Previous random element</div>
<div value="" class="crossbrowser-select" tabindex="0">
<div class="visual-option">Select Item from list</div>
<div class="option" value="1option">Option1</div>
<div class="option" value="2option">Option2</div>
<div class="option" value="3option">Option3</div>
</div>
<div style="margin-top: 20px">Next random element</div>
</div>
<script src="https://code.jquery.com/jquery-1.12.3.js" ></script>
</body>
</html>
Related
I'm trying to create a simple drag & drop example to use that will allow swapping of items. For example:
Item 0
Item 1
Item 2
Item 3
If I drag and drop "Item 0" over "Item 3" they should swap places. What I have below does not swap the correct elements, will also make some slots "un-droppable" and error out due to e.dataTransfer not providing any data.
const log = console.log.bind(console);
const $ = document.getElementById.bind(document);
function drop(e) {
e.preventDefault();
let dragindex = 0;
let clone = e.target.cloneNode(true);
let data = e.dataTransfer.getData("text/plain");
if (clone.dataset.id !== data) {
[...$("container").children].forEach((el, i) => {
if (el.dataset.id == data) {
dragindex = +i;
}
})
log(data, clone.dataset.id, dragindex, e.target.dataset.id);
$("container").replaceChild(document.querySelector(`[data-id=${data}]`), e.target);
$("container").insertBefore(clone, $("container").childNodes[dragindex]);
}
}
[...document.querySelectorAll(".draggable")].map((el) => {
el.setAttribute("draggable", true);
});
[...document.querySelectorAll(".draggable")].map((el) => {
el.addEventListener("dragover", (e) => {
e.preventDefault();
})
el.addEventListener("dragstart", (e) => {
e.dataTransfer.setData("text/plain", e.target.dataset.id);
});
el.addEventListener("drop", (e) => {
drop(e);
});
})
#container {
width: 200px;
height: auto;
position: absolute;
left: 50%;
top: 50%;
background: dodgerblue;
color: #fff;
transform: translate(-50%, -50%);
border: 1px solid #000;
}
.draggable {
display: flex;
justify-content: start;
align-items: center;
border: 1px solid #fff;
margin: 2px;
padding: .5em;
text-align: center;
cursor: grab;
}
.draggable i {
margin-right: 25px;
}
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<div id="container">
<div class="draggable" data-id="drag0"><i class="material-icons">drag_indicator</i>Draggable 0</div>
<div class="draggable" data-id="drag1"><i class="material-icons">drag_indicator</i>Draggable 1</div>
<div class="draggable" data-id="drag2"><i class="material-icons">drag_indicator</i>Draggable 2</div>
<div class="draggable" data-id="drag3"><i class="material-icons">drag_indicator</i>Draggable 3</div>
</div>
So.... I finally cracked it. It was several things.
You have to re-add event listeners to a cloned node if they were added via "document.addEventListener()".
Had to use ".childNodes" not ".children" as the indexing does not work out the same.
Had to take care where/when I created the variable holding the reference node.
Also figured out that it acts weird in Safari on IOS if the drag/drop parent container is absolutely positioned so need to use flex positioning, as well as a few other minor details; any how, in case any one finds it helpful, here is the working code. Works in Android-Chrome/IOS-Safari.
const log = console.log.bind(console);
const $ = document.getElementById.bind(document);
function drop(e) {
e.preventDefault();
let dragindex = 0;
let referenceNode = "";
let clone = e.target.cloneNode(true);
addListeners(clone);
let data = e.dataTransfer.getData("text/plain");
if (clone.dataset.id !== data) {
[...$("container").childNodes].forEach((el, i) => {
if (el.dataset?.id == data) {
dragindex = i;
}
});
$("container").replaceChild(
document.querySelector(`[data-id=${data}]`),
e.target
);
referenceNode = $("container").childNodes[dragindex];
$("container").insertBefore(clone, referenceNode);
clone.classList.remove("dragActive");
}
}
function addListeners(el) {
el.addEventListener("dragover", (e) => {
e.preventDefault();
e.target.classList.add("dragActive");
});
el.addEventListener("dragstart", (e) => {
e.dataTransfer.setData("text/plain", e.target.dataset.id);
});
el.addEventListener("dragleave", (e) => {
e.target.classList.remove("dragActive");
});
el.addEventListener("dragend", (e) => {
e.target.classList.remove("dragActive");
});
el.addEventListener("drop", (e) => {
e.target.classList.remove("dragActive");
drop(e);
});
}
[...document.querySelectorAll(".draggable")].map((el) => {
el.setAttribute("draggable", true);
});
[...document.querySelectorAll(".draggable")].map((el) => {
addListeners(el);
});
html,
body {
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
width: 100%;
height: 100%;
}
#container {
width: 200px;
height: auto;
background: dodgerblue;
color: #fff;
border: 1px solid #000;
position: absolute;
/* top: 50%;
left: 50%;
transform: translate(-50%, -50%); */
}
.draggable {
border: 1px solid #fff;
margin: 2px;
padding: .5em;
text-align: center;
cursor: grab;
color: #000;
background: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACMAAAAzCAYAAAAdD7HCAAAACXBIWXMAAA7DAAAOwwHHb6hkAAADGElEQVRYhe1Zy2oUURA9MSoiWYQRxEdAMBoDxpVGZhFQF5qV+AgSPyK6CPgFbswvCD4WrkQQHwsFDUY3JuomISjic8CZhYk6PtCoUev07Rlm2p7uPj2TXR84zUxSValO31t16nYb6rHM2G/sMf40PjG+QGvQaTxo7DX+Nk4Z7xp/hBkfMr4y/g1w3LityURGjV9CYheMg0HjkRDDWpaNO1MmMhYTexHuH+Ghz/grxoF8aVwpJjKQIC45b8zR4VJCB/K4mMxVIfYJLtg9QvBBMZndgu1eJtMlOKyFhpxg28FkCoJDCRreCLZvmcwdweEmNFwTbK/wssW4gPgFNgNXFBXwMb1PEHui1mkY0du75CedBnnjx4jY08Z1QSfuqsmAIRO8DG2Rh2GT8SLqq3DReNq4umLUFuK42dgN1z+Y9TxaBxbN9X7sd8iQIcMSIWxrrzH2+p+foXVbm9V7l3GH/30WTnr+CTOmtGTvofKqLXrXjd1NJrLP/+PB6jvr/64OLNllNC7ZLOdpZecQolsNb/5YxbgDrvfENbOSb6uAPaecIPY32rbb5aTxaILATGTO+FBI5pTxQAK7FXCjER4guU69DQ1K7EmucEUabhCT6RRsPdn5VXD4AA1FwXZOlZ33oOGWYHuDF654rua4Z1pGiCKLQaqdStm5GGHMOjGEdOBBQpTs5E3mg05SlRSxFa6S1xY/3jwrfvVQIexIhFPgdv87J4LHaNA/UmCp+l6GDBnq0N7g5xvhGuh3uHrQKnBrs3T0+HHLjQw583L2ZXOrFCbOxufhZuVmwFmdM3tQ8XG2/+/kjD1nGo1LNotTPmUiPL2I6k9McLjWYQLxzYznLDkxEVb0mQSxF/ykPVmYVI2dEZM5LMQ+R4ezgsNTMZkLQmzvTE9ZnOqhkSJTu1TZ+RkaFNlZZDL3BYcpaFAkrXfIyB3CrZvkuQ6IyfDY7HWCuNzefRWnI4iWneQY0oFjcdxUORJ04nuBQoghq/AomgOl5XhIbL7fqr7eCcrOVcb9cEcXy+GkIUeIT2gNWNj6/djPjY9QlbTAPz6/t2nPvICTAAAAAElFTkSuQmCC');
background-repeat: no-repeat;
background-size: 15px;
background-position: 5px;
position: relative;
}
.dragActive {
background: rgba(255, 255, 255, .25);
color: #000;
border: 1px solid #000;
}
<div id="container">
<div class="draggable" data-id="drag0">Draggable 0</div>
<div class="draggable" data-id="drag1">Draggable 1</div>
<div class="draggable" data-id="drag2">Draggable 2</div>
<div class="draggable" data-id="drag3">Draggable 3</div>
</div>
I'm looking for advice/tips on how to fix a function that is supposed to remove items from localStorage. I'm following a tutorial by John Smilga that I found on Youtube. Although I've modeled my code on his, apparently, I have missed something.
This function works perfectly well if I run it manually from the console and pass in the id of the item that I want to remove from localStorage.
function removeFromLocalStorage(id) {
console.log(id);
let storageItems = getLocalStorage();
console.log(storageItems);
storageItems = storageItems.filter(function(singleItem) {
if (singleItem.id !== id) {
return singleItem;
}
})
console.log(storageItems);
localStorage.setItem("list", JSON.stringify(storageItems));
}
However, when this function is triggered by the deleteItem() function, it refuses to remove the item from localStorage. It still works, there are a bunch of console.logs in it that track its execution, and I can check that it receives the correct item id as the argument, but for some reason it doesn't filter out the item that needs to be removed. I am completely lost and have no idea how to identify the problem. I can't debug it with console.logs as I usually do. I will be very grateful if you help me find the problem. Any advice will be appreciated.
In case the entire code is needed, please find it below.
const form = document.querySelector(".app__form");
const alert = document.querySelector(".app__alert");
const input = document.querySelector(".app__input");
const submitBtn = document.querySelector(".app__submit-btn");
const itemsContainer = document.querySelector(".app__items-container");
const itemsList = document.querySelector(".app__items-list");
const clearBtn = document.querySelector(".app__clear-btn");
let editElement;
let editFlag = false;
let editId = "";
form.addEventListener("submit", addItem);
clearBtn.addEventListener("click", clearItems);
function addItem(e) {
e.preventDefault();
const id = Math.floor(Math.random() * 9999999999);
if (input.value && !editFlag) {
const item = document.createElement("div");
item.classList.add("app__item");
const attr = document.createAttribute("data-id");
attr.value = id;
item.setAttributeNode(attr);
item.innerHTML = `<p class='app__item-text'>${input.value}</p>
<div class='app__item-btn-cont'>
<button class='app__item-btn app__item-btn--edit'>edit</button>
<button class='app__item-btn app__item-btn--delete'>delete</button>
</div>`
const editBtn = item.querySelector(".app__item-btn--edit");
const deleteBtn = item.querySelector(".app__item-btn--delete");
editBtn.addEventListener("click", editItem);
deleteBtn.addEventListener("click", deleteItem);
itemsList.appendChild(item);
displayAlert("item added", "success");
addToLocalStorage(id, input.value);
setBackToDefault();
itemsContainer.classList.add("app__items-container--visible");
} else if (input.value && editFlag) {
editElement.textContent = input.value;
// edit local storage
editLocalStorage(editId, input.value);
setBackToDefault();
displayAlert("item edited", "success");
} else {
displayAlert("empty field", "warning");
}
}
function setBackToDefault() {
input.value = "";
editFlag = false;
editId = "";
submitBtn.textContent = "Submit";
submitBtn.className = "app__submit-btn";
}
function displayAlert(text, action) {
alert.textContent = text;
alert.classList.add(`app__alert--${action}`);
setTimeout(function() {
alert.textContent = "";
alert.classList.remove(`app__alert--${action}`);
}, 700)
}
function clearItems() {
const items = document.querySelectorAll(".app__item");
if (items.length > 0) {
items.forEach(function(singleItem) {
itemsList.removeChild(singleItem);
})
itemsContainer.classList.remove("app__items-container--visible");
displayAlert("items cleared", "cleared");
setBackToDefault();
}
}
function editItem(e) {
const item = e.currentTarget.parentElement.parentElement;
editElement = e.currentTarget.parentElement.previousElementSibling;
editId = item.dataset.id;
editFlag = true;
input.value = editElement.textContent;
submitBtn.textContent = "Edit";
submitBtn.classList.add("app__submit-btn--edit");
input.focus();
}
function deleteItem(e) {
const item = e.currentTarget.parentElement.parentElement;
const itemId = item.dataset.id;
removeFromLocalStorage(itemId);
displayAlert("item removed", "cleared");
setBackToDefault();
itemsList.removeChild(item);
if (itemsList.children.length === 0) {
itemsContainer.classList.remove("app__items-container--visible");
}
}
function addToLocalStorage(id, value) {
const itemsObj = {id: id, value: input.value};
let storageItems = getLocalStorage();
storageItems.push(itemsObj);
localStorage.setItem("list", JSON.stringify(storageItems));
}
function removeFromLocalStorage(id) {
console.log(id);
let storageItems = getLocalStorage();
console.log(storageItems);
storageItems = storageItems.filter(function(singleItem) {
if (singleItem.id !== id) {
return singleItem;
}
})
console.log(storageItems);
localStorage.setItem("list", JSON.stringify(storageItems));
}
function editLocalStorage(id, value) {
}
function getLocalStorage() {
return localStorage.getItem("list") ? JSON.parse(localStorage.getItem("list")) : [];
}
* {
margin: 0;
padding: 0;
}
.app {
width: 70%;
max-width: 600px;
margin: 75px auto 0;
}
.app__title {
text-align: center;
/* color: #1B5D81; */
margin-top: 20px;
color: #377FB4;
}
.app__alert {
width: 60%;
margin: 0 auto;
text-align: center;
font-size: 20px;
color: #215884;
border-radius: 7px;
height: 23px;
transition: 0.4s;
text-transform: capitalize;
}
.app__alert--warning {
background-color: rgba(243, 117, 66, 0.2);
color: #006699;
}
.app__alert--success {
background-color: rgba(165, 237, 92, 0.4);
color: #3333ff;
}
.app__alert--cleared {
background-color: #a978da;
color: white;
}
.app__input-btn-cont {
display: flex;
margin-top: 30px;
}
.app__input {
width: 80%;
box-sizing: border-box;
font-size: 20px;
padding: 3px 0 3px 10px;
border-top-left-radius: 10px;
border-bottom-left-radius: 10px;
border-right: none;
border: 1px solid #67B5E2;
background-color: #EDF9FF;
}
.app__input:focus {
outline: transparent;
}
.app__submit-btn {
display: block;
width: 20%;
border-top-right-radius: 10px;
border-bottom-right-radius: 10px;
border-left: none;
background-color: #67B5E2;
border: 1px solid #67B5E2;
cursor: pointer;
font-size: 20px;
color: white;
transition: background-color 0.7s;
padding: 3px 0;
}
.app__submit-btn--edit {
background-color: #95CB5D;
}
.app__submit-btn:active {
width: 19.9%;
padding: 0 0;
}
.app__submit-btn:hover {
background-color: #377FB4;
}
.app__submit-btn--edit:hover {
background-color: #81AF51;
}
.app__items-container {
visibility: hidden;
/* transition: 0.7s; */
}
.app__items-container--visible {
visibility: visible;
}
.app__item {
display: flex;
justify-content: space-between;
margin: 20px 0;
}
.app__item:hover {
background-color: #b9e2fa;
border-radius: 10px;
}
.app__item-text {
padding-left: 10px;
font-size: 20px;
color: #1B5D81;
}
.app__item-btn-cont {
display: flex;
}
.app__item-btn-img {
width: 20px;
height: 20px;
}
.app__item-btn {
border: none;
background-color: transparent;
cursor: pointer;
display: block;
font-size: 18px;
}
.app__item-btn--edit {
margin-right: 45px;
color: #2c800f;
}
.app__item-btn--delete {
margin-right: 15px;
color: rgb(243, 117, 66);
}
.app__clear-btn {
display: block;
width: 150px;
margin: 20px auto;
border: none;
background-color: transparent;
font-size: 20px;
color: rgb(243, 117, 66);
letter-spacing: 2px;
cursor: pointer;
transition: border 0.3s;
border: 1px solid transparent;
}
.app__clear-btn:hover {
border: 1px solid rgb(243, 117, 66);
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8" name="viewport" content="width=device-width,
initial-scale=1">
<link rel="stylesheet" href="list.css">
<title>To Do List App</title>
</head>
<body>
<section class="app">
<form class="app__form">
<p class="app__alert"></p>
<h2 class="app__title">To Do List</h2>
<div class="app__input-btn-cont">
<input class="app__input" type="text" id="todo" placeholder="do stuff">
<button class="app__submit-btn">Submit</button>
</div>
</form>
<div class="app__items-container">
<div class="app__items-list">
</div>
<button class="app__clear-btn">Clear Items</button>
</div>
</section>
<script src="list.js"></script>
</body>
</html>
Your code is fine you just used the wrong comparison operator.
In your case you are comparing 2 IDs (operands) to see if they match up, so you should use normal operators such as (==, !=), but instead in your case, you have used strict operators which are used to compare the operand type and the operand itself.
You can learn more about Comparison Operators here.
Ultimatly,
In your function removeFromLocalStorage(id), you have an extra equal sign in your if function.
Instead of:
if (singleItem.id !== id) {
return singleItem;}
It should be:
if (singleItem.id != id) {
return singleItem;}
Hope this helps.
I don’t want use or i don't know how to use 'the CSS:after prototype' by javascript .
Now, I change it is by add height not width,and when i remove the class prototype, reback is a short time,no transtion.
What can i do for it?
this is my codepen link
<div class="block">
<div id="top">my block/div>
<div>
<button id="btn">submit</button>
</div>
</div>
.block {
height: 200px;
width: 250px;
margin:150px auto;
text-align: center;
}
#top {
margin-bottom: 20px;
height: 30px;
display: inline-block;
border-bottom: 3px solid;
transition: 1s all cubic-bezier(.46, 1, .23, 1.52);
}
.addtop {
border-bottom: 3px solid blue;
color: blue;
}
let btn = document.getElementById('btn');
btn.addEventListener('click',() => {
let topBlock = document.getElementById('top');
if(topBlock.classList.length > 0) {
topBlock.classList = [];
} else {
topBlock.classList.add('addtop');
}
});
Try this:
document.getElementById('top');
if(topBlock.classList.length > 0) {
topBlock.classList.remove('addtop');
} else {
topBlock.classList.add('addtop');
}
});
Also add to .top class:
border-bottom: 0px solid blue;
I have this simple Modal that's shows up upon clicking button and a Page inside it, depends of which button is click,
uno is for page1, dos is for page2 tres is for page3.
the whole box is a button and i have h3 inside it(It's for the title of that button), but when i click the green area which is H3 my pages does not shos up.
I know the problem is that when it clicks h3 it targets the h3 and h3 has ni ID in it.
Can someone help me to make my h3 act as div when i click it?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.myBtn {
width: 100px;
height: 100px;
background-color: aqua;
margin: 10px;
text-align: center;
}
.myBtn h3 {
background-color:green;
line-height: 2;
cursor: pointer;
}
.myBtn:hover {
background-color: aquamarine;;
}
.btns {
float: left;
}
.modal {
display: none;
background-color: aqua;
float: right;
width: 400px;
height: 600px;
}
.page1 {
position: absolute;
display: none;
background-color: burlywood;
margin: 20px;
width: 300px;
height: 150px;
}
.p1 {
border: 2px solid red;
}
.p2 {
border: 2px solid blue;
}
.p3 {
border: 2px solid green;
}
</style>
</head>
<body>
<p>Click the button to Show Modal.</p>
<div class="btns">
<div class="myBtn" id="uno">
<h3>uno</h3>
</div>
<div class="myBtn " id="dos">
<h3>dos</h3>
</div>
<div class="myBtn "id="tres">
<h3>tres</h3></div>
</div>
<div class="modal">
Modal
<div class="page1 p1">Page1</div>
<div class="page1 p2">Page2</div>
<div class="page1 p3">Page3</div>
</div>
<!--JS-->
<script>
var btn = document.querySelectorAll('.myBtn');
var getModal = document.querySelector('.modal');
var getPages = document.querySelectorAll('.page1');
//console.log(getPages);
for(let i=0; i<btn.length;i++ ){
btn[i].addEventListener('click', () => {
hideModal();
getId();
displayPage()});
}
function hideModal(){
getModal.style.display = "block";
}
function getId(){
//console.log(event.target.id);
}
function hideall(){
for(let i=0; i<getPages.length;i++ ){
getPages[i].style.display = 'none';
}
}
function displayPage(){
hideall();
var btnId = event.target.id;
console.log(btnId);
if(btnId == "uno"){
getPages[0].style.display = "block";
}else if(btnId == "dos"){
getPages[1].style.display = "block";
}else if(btnId == "tres"){
getPages[2].style.display = "block";
}
console.log(getPages[0]);
}
window.addEventListener('click', closeIfOutside);
function closeIfOutside(e) {
if(e.target == getModal)
{
getModal.style.display = 'none';
}
}
</script>
</body>
</html>
<html>
You can add pointer-events: none to your h3 elements so that any clicks will fall through to the containing parent div behind it, allowing you to get the correct id to show the correct page:
.myBtn h3 {
background-color: green;
line-height: 2;
cursor: pointer;
pointer-events: none;
}
See example below:
var btn = document.querySelectorAll('.myBtn');
var getModal = document.querySelector('.modal');
var getPages = document.querySelectorAll('.page1');
//console.log(getPages);
for (let i = 0; i < btn.length; i++) {
btn[i].addEventListener('click', () => {
hideModal();
getId();
displayPage()
});
}
function hideModal() {
getModal.style.display = "block";
}
function getId() {
//console.log(event.target.id);
}
function hideall() {
for (let i = 0; i < getPages.length; i++) {
getPages[i].style.display = 'none';
}
}
function displayPage() {
hideall();
var btnId = event.target.id;
//console.log(btnId);
if (btnId == "uno") {
getPages[0].style.display = "block";
} else if (btnId == "dos") {
getPages[1].style.display = "block";
} else if (btnId == "tres") {
getPages[2].style.display = "block";
}
//console.log(getPages[0]);
}
window.addEventListener('click', closeIfOutside);
function closeIfOutside(e) {
if (e.target == getModal) {
getModal.style.display = 'none';
}
}
.myBtn {
width: 100px;
height: 100px;
background-color: aqua;
margin: 10px;
text-align: center;
}
.myBtn h3 {
background-color: green;
line-height: 2;
cursor: pointer;
pointer-events: none;
}
.myBtn:hover {
background-color: aquamarine;
;
}
.btns {
float: left;
}
.modal {
display: none;
background-color: aqua;
float: right;
width: 400px;
height: 600px;
}
.page1 {
position: absolute;
display: none;
background-color: burlywood;
margin: 20px;
width: 300px;
height: 150px;
}
.p1 {
border: 2px solid red;
}
.p2 {
border: 2px solid blue;
}
.p3 {
border: 2px solid green;
}
<p>Click the button to Show Modal.</p>
<div class="btns">
<div class="myBtn" id="uno">
<h3>uno</h3>
</div>
<div class="myBtn " id="dos">
<h3>dos</h3>
</div>
<div class="myBtn " id="tres">
<h3>tres</h3>
</div>
</div>
<div class="modal">
Modal
<div class="page1 p1">Page1</div>
<div class="page1 p2">Page2</div>
<div class="page1 p3">Page3</div>
</div>
I would please like an explanation to why the slideshow is not working. Below I have used an interval to perpetually change the slideshow, if userClick is false. The white and squared buttons (made of divs) are set to call upon two functions; slideRight() or slideLeft() and clicked(). When the buttons are clicked however, the clicked() function does not seem to change the variable, based on the data on top of the page.
<body>
<div class="page-wrapper">
<header>
<div class="headContent">
<h1 class="titleText">Slideshow</h1>
<h2 class="subTitleText">A slideshow made with JavaScript.</h2>
<p>userClick <span id="uc"></span></p>
</div>
<nav>
<ul>
<li>Home</li>
<li>About</li>
<li>Gallery</li>
</ul>
</nav>
</header>
<div class="body-wrapper">
<h1 class="titleText">Slideshow</h1>
<div id="slideshow">
<div id="leftSlide" onclick="leftSlide(); clicked()"></div>
<div id="rightSlide" onclick="rightSlide(); clicked()"></div>
</div>
<p>The image is not invoked by a tag, but invoked by the background property using Javascript.</p>
</div>
<footer>
<p id="footerText">© 2017 <br>Designed by JastineRay</p>
</footer>
</div>
<script language="javascript">
// Slide function
var slide = ["minivan", "lifeinthecity", "sunsetbodyoflove"];
var slideTo = 1;
window.onload = getSlide();
// Previous Image
function leftSlide() {
if (slideTo != 0) {
slideTo = slideTo - 1;
} else if (slideTo == 0) {
slideTo = slide.length - 1;
} else {
alert('SLIDE ERROR');
}
getSlide();
}
// Next Image
function rightSlide() {
if (slideTo != (slide.length - 1)) {
slideTo = slideTo + 1;
} else if (slideTo == (slide.length - 1)) {
slideTo = 0;
} else {
alert('SLIDE ERROR');
}
getSlide();
}
function getSlide() {
imageURL = 'url(images/' + slide[slideTo] + '.jpg)';
document.getElementById("slideshow").style.backgroundImage = imageURL;
}
// Interval Slideshow & Check if user clicked (timeout)
var userClick = false;
window.onload = slideInterval(5000);
// Start Slideshow
function slideInterval(interval) {
while (userClick = false) {
setInterval(function() {
rightSlide();
}, interval)
}
}
// Stop Slideshow and start timeout
function clicked() {
userClick = true;
setTimeout(function() {
userClick = false;
slideInterval();
}, 2000)
}
window.onload = function() {
setInterval(document.getElementById("uc").innerHTML = userClick), 100
}
</script>
</body>
CSS coding below.
* {
margin: 0;
padding: 0;
}
.page-wrapper {
width: 100%;
}
// Class Styling
.titleText {
font-family: monospace;
font-size: 40px;
}
.subTitleText {
font-family: monospace;
font-size: 20px;
font-weight: normal;
}
// Header Styling
header {
height: 500px;
}
.headContent {
margin: 30px 7%;
}
// Navigation Styling
nav {
overflow: hidden;
}
nav ul {
background: black;
background: linear-gradient(#595959, black);
list-style-type: none;
font-size: 0;
padding-left: 13.33%;
margin: 40px 0;
}
nav ul li {
padding: 15px 20px;
border-right: 1px solid #595959;
border-left: 1px solid #595959;
color: white;
display: inline-block;
font-size: 20px;
font-family: sans-serif;
}
// Body Styling
.body-wrapper {
}
.body-wrapper > .titleText {
text-align: center;
font-size: 50px;
}
#slideshow {
overflow: hidden;
margin: 20px auto;
border: 2px solid blue;
height: 350px;
max-width: 800px;
background-size: cover;
background-position: center;
position: relative;
}
#leftSlide {
position: absolute;
left: 40px;
top: 175px;
background-color: white;
height: 40px;
width: 40px;
}
#rightSlide {
position: absolute;
left: 100px;
top: 175px;
background-color: white;
height: 40px;
width: 40px;
}
// Footer Styling
Try changing the checking part to:
window.onload = function() {
setInterval(function () {
document.getElementById("uc").innerHTML = userClick;
}, 100);
}
The first argument of setInterval has to be a function (something that can be called), not a generic piece of code.