I was creating a dropdown menu which when hovered upon displays sub-links.
But, I ran into a problem as when I hover on the dropdown, it shows a blank box and only shows the text when hovered upon it specifically.
I want that the text to be displayed at all times.
// Sticky Navbar
var h = document.getElementById("navbar");
var stuck = false;
var stickPoint = getDistance();
function getDistance() {
var topDist = h.offsetTop;
return topDist;
}
window.onscroll = function(e) {
var distance = getDistance() - window.pageYOffset;
var offset = window.pageYOffset;
if ( (distance <= 0) && !stuck) {
h.style.position = 'fixed';
h.style.top = '0px';
stuck = true;
} else if (stuck && (offset <= stickPoint)){
h.style.position = 'static';
stuck = false;
}
}
// Preloader
const preloader = document.querySelector('.preloader');
const fadeEffect = setInterval(() => {
// if we don't set opacity 1 in CSS, then //it will be equaled to "", that's why we // check it
if (!preloader.style.opacity) {
preloader.style.opacity = 1;
}
if (preloader.style.opacity > 0) {
preloader.style.opacity -= 0.1;
} else {
clearInterval(fadeEffect);
}
}, 200);
window.addEventListener('load', fadeEffect);
/* Navbar */
#navbar {
height: 75px;
display: block;
background: #333;
width: 100%;
}
#navbar a{
font-size: 16px;
color: white;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}
.dropdown {
padding-top: 10px;
text-align: center;
}
.dropdown .dropbtn {
font-size: 16px;
border: none;
outline: none;
color: white;
padding: 14px 16px;
background-color: inherit;
font-family: inherit;
margin: 0;
}
#navbar a:hover, .dropdown:hover .dropbtn {
background-color: silver;
color: black;
}
.dropdown-content {
display: none;
position: absolute;
margin-left: 49%;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}
.dropdown-content a {
display: inline-block;
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
text-align: left;
}
.dropdown-content a:hover {
background-color: #ddd;
}
.dropdown:hover .dropdown-content {
display: block;
}
<!-- Navbar -->
<div id="navbar">
<div class="dropdown">
<button class="dropbtn">Projects
<i class="fa fa-caret-down"></i>
</button>
<div class="dropdown-content">
Drum Kit
Coming Soon...
</div>
</div>
</div>
Apart from this, I have implemented the Sticky Navbar and a Simple Preloader using Vanilla JS which I am sharing if it might help.
Just help me with the dropdown thing.
Any help will be appreciated.
As #Y.S. point out you have color set to white. Not sure what you've tried that didn't work, this works fine for me:
// Sticky Navbar
var h = document.getElementById("navbar");
var stuck = false;
var stickPoint = getDistance();
function getDistance() {
var topDist = h.offsetTop;
return topDist;
}
window.onscroll = function(e) {
var distance = getDistance() - window.pageYOffset;
var offset = window.pageYOffset;
if ( (distance <= 0) && !stuck) {
h.style.position = 'fixed';
h.style.top = '0px';
stuck = true;
} else if (stuck && (offset <= stickPoint)){
h.style.position = 'static';
stuck = false;
}
}
// Preloader
const preloader = document.querySelector('.preloader');
const fadeEffect = () =>
{
setInterval(() => {
// if we don't set opacity 1 in CSS, then //it will be equaled to "", that's why we // check it
if (!preloader.style.opacity) {
preloader.style.opacity = 1;
}
if (preloader.style.opacity > 0) {
preloader.style.opacity -= 0.1;
} else {
clearInterval(fadeEffect);
}
}, 200);
}
window.addEventListener('load', fadeEffect);
/* Navbar */
#navbar {
height: 75px;
display: block;
background: #333;
width: 100%;
}
#navbar a{
font-size: 16px;
color: black;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}
.dropdown {
padding-top: 10px;
text-align: center;
}
.dropdown .dropbtn {
font-size: 16px;
border: none;
outline: none;
color: white;
padding: 14px 16px;
background-color: inherit;
font-family: inherit;
margin: 0;
}
#navbar a:hover, .dropdown:hover .dropbtn {
background-color: silver;
color: black;
}
.dropdown-content {
display: none;
position: absolute;
margin-left: 49%;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}
.dropdown-content a {
display: inline-block;
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
text-align: left;
}
.dropdown-content a:hover {
background-color: #ddd;
}
.dropdown:hover .dropdown-content {
display: block;
}
<!-- Navbar -->
<div id="navbar">
<div class="dropdown">
<button class="dropbtn">Projects
<i class="fa fa-caret-down"></i>
</button>
<div class="dropdown-content">
Drum Kit
Coming Soon...
</div>
</div>
</div>
<div class="preloader"></div>
So I'm working on this simple project. It's a To-Do List. Every task has to buttons, namely, done and delete (These are images). And there are two divisions, one will store the pending tasks and the other will stored the completed tasks.
I want that when the user clicks on the done button (tick image) the task should be removed from the "Pending Tasks" division and shifted to the "Completed Tasks" division. I tried to add this functionality by adding an event listener to the images. The event listens for a single click. But the code is not working properly. For the first task, I've to click twice to remove it. The same is the case with other tasks as well. Which means every single task is added twice to the "Completed Tasks" division.
Also, I've added functionality to add new tasks. But the buttons (images) don't work on these new tasks. Basically, event listening is not working on them. Kindly help with the issue. I've added the code below.
(I've not added any functionality for deletion)
var completedTasks = document.querySelector(".Completed-Tasks");
var pendingTasks = document.querySelector(".Pending-Tasks");
var addTaskButton = document.querySelector(".Add-Task-Button");
var doneButtons = document.querySelectorAll(".Tick");
var deleteButtons = document.querySelectorAll(".Cross");
doneButtons.forEach(checkClickEvent);
console.log(doneButtons.length);
function checkClickEvent(button, index) {
button.addEventListener("click", function() {
let task = button.parentNode.parentNode;
pendingTasks.removeChild(pendingTasks.childNodes[index]);
let doneTaskHTML = `<div class="Task Done"><p class="Task-Text">${task.children[0].textContent}</p><div class="Task-Operations"><img src="./Cross.png" alt="Delete" class="Operation"></div></div>`;
completedTasks.insertAdjacentHTML("beforeend", doneTaskHTML);
});
}
addTaskButton.addEventListener("click", function(event) {
event.preventDefault();
let newTaskText = document.querySelector(".Add-Task-Input");
if (newTaskText.value != "") {
let newTaskHTML = `<div class="Task"><p class="Task-Text">${newTaskText.value}</p><div class="Task-Operations"><img src="./Tick.png" alt="Done" class="Operation Tick"><img src="./Cross.png" alt="Delete" class="Operation Cross"></div></div>`;
pendingTasks.insertAdjacentHTML("beforeend", newTaskHTML);
newTaskText.value = "";
}
});
#import url('https://fonts.googleapis.com/css2?family=Poppins&display=swap');
* {
margin: 0px;
padding: 0px;
box-sizing: border-box;
font-family: "Poppins";
}
body {
background: #EDF2F4;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
min-height: 100vh;
}
.Header {
background: #2B2D42;
color: #FFFFFF;
max-width: 500px;
width: 100%;
padding: 15px;
margin-bottom: 20px;
}
.Heading {
font-size: 25px;
text-align: center;
}
.Tasks-Space {
background: #8D99AE;
max-width: 500px;
width: 100%;
padding: 15px;
position: relative;
}
.Add-Task {
position: relative;
width: 100%;
}
.Add-Task-Input {
outline: none;
border: none;
padding: 5px 10px;
width: 100%;
font-size: 16px;
}
.Add-Task-Button {
outline: none;
border: none;
width: 100%;
padding: 5px 10px;
margin-top: 15px;
font-size: 16px;
cursor: pointer;
background: #D90429;
color: #FFFFFF;
}
.Add-Task-Button:hover {
background: #EF233C;
color: #FFFFFF;
}
.Tasks-Space-Heading {
margin-top: 15px;
padding: 5px 10px;
background: #2B2D42;
color: #FFFFFF;
}
.Pending-Tasks {
margin-top: 15px;
}
.Completed-Tasks {
margin-top: 15px;
}
.Task {
background: #FFFFFF;
padding: 5px 10px;
display: flex;
align-items: center;
justify-content: space-between;
}
.Task-Operations {
display: flex;
align-items: center;
}
.Operation {
height: 20px;
margin-left: 10px;
cursor: pointer;
}
.Done {
text-decoration: line-through;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>To-Do List</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<div class="Header">
<p class="Heading">TO-DO LIST</p>
</div>
<div class="Tasks-Space">
<div class="Add-Task">
<input type="text" placeholder="Enter your task here" class="Add-Task-Input">
<button class="Add-Task-Button">Add Task</button>
</div>
<p class="Tasks-Space-Heading">Pending Tasks</p>
<div class="Pending-Tasks">
<div class="Task">
<p class="Task-Text">Make a pie</p>
<div class="Task-Operations">
<img src="./Tick.png" alt="Done" class="Operation Tick">
<img src="./Cross.png" alt="Delete" class="Operation Cross">
</div>
</div>
<div class="Task">
<p class="Task-Text">Play Minecraft</p>
<div class="Task-Operations">
<img src="./Tick.png" alt="Done" class="Operation Tick">
<img src="./Cross.png" alt="Delete" class="Operation Cross">
</div>
</div>
</div>
<p class="Tasks-Space-Heading">Completed Tasks</p>
<div class="Completed-Tasks"></div>
</div>
<script src="./main.js"></script>
</body>
</html>
Instead of pendingTasks.removeChild(pendingTasks.childNodes[index]); do task.remove(); since you already have the node that you want to remove. here is the reference to remove() function.
Also added document.querySelectorAll(".Tick").forEach(checkClickEvent); in add task click handler. This should add event listener to newly added tasks as well.
Edited
The solution did work but there was a slight problem. When we are adding event listeners to the new tasks using document.querySelectorAll(".Tick").forEach(checkClickEvent);, multiple event listeners are getting added to the existing tasks. To avoid this simply reinitialize the HTML inside the division. This can be done using pendingTasks.innerHTML = pendingTasks.innerHTML;. This code will remove all the existing event listeners on any element inside the division. Note that this code has to be used before adding event listeners again.
var completedTasks = document.querySelector(".Completed-Tasks");
var pendingTasks = document.querySelector(".Pending-Tasks");
var addTaskButton = document.querySelector(".Add-Task-Button");
var doneButtons = document.querySelectorAll(".Tick");
var deleteButtons = document.querySelectorAll(".Cross");
doneButtons.forEach(checkClickEvent);
console.log(doneButtons.length);
function checkClickEvent(button, index) {
button.addEventListener("click", function() {
let task = button.parentNode.parentNode;
task.remove();
let doneTaskHTML = `<div class="Task Done"><p class="Task-Text">${task.children[0].textContent}</p><div class="Task-Operations"><img src="./Cross.png" alt="Delete" class="Operation"></div></div>`;
completedTasks.insertAdjacentHTML("beforeend", doneTaskHTML);
});
}
addTaskButton.addEventListener("click", function(event) {
event.preventDefault();
let newTaskText = document.querySelector(".Add-Task-Input");
if (newTaskText.value != "") {
let newTaskHTML = `<div class="Task"><p class="Task-Text">${newTaskText.value}</p><div class="Task-Operations"><img src="./Tick.png" alt="Done" class="Operation Tick"><img src="./Cross.png" alt="Delete" class="Operation Cross"></div></div>`;
pendingTasks.insertAdjacentHTML("beforeend", newTaskHTML);
newTaskText.value = "";
pendingTasks.innerHTML = pendingTasks.innerHTML; // Re-initialize
document.querySelectorAll(".Tick").forEach(checkClickEvent); // Adding event listeners again
}
});
#import url('https://fonts.googleapis.com/css2?family=Poppins&display=swap');
* {
margin: 0px;
padding: 0px;
box-sizing: border-box;
font-family: "Poppins";
}
body {
background: #EDF2F4;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
min-height: 100vh;
}
.Header {
background: #2B2D42;
color: #FFFFFF;
max-width: 500px;
width: 100%;
padding: 15px;
margin-bottom: 20px;
}
.Heading {
font-size: 25px;
text-align: center;
}
.Tasks-Space {
background: #8D99AE;
max-width: 500px;
width: 100%;
padding: 15px;
position: relative;
}
.Add-Task {
position: relative;
width: 100%;
}
.Add-Task-Input {
outline: none;
border: none;
padding: 5px 10px;
width: 100%;
font-size: 16px;
}
.Add-Task-Button {
outline: none;
border: none;
width: 100%;
padding: 5px 10px;
margin-top: 15px;
font-size: 16px;
cursor: pointer;
background: #D90429;
color: #FFFFFF;
}
.Add-Task-Button:hover {
background: #EF233C;
color: #FFFFFF;
}
.Tasks-Space-Heading {
margin-top: 15px;
padding: 5px 10px;
background: #2B2D42;
color: #FFFFFF;
}
.Pending-Tasks {
margin-top: 15px;
}
.Completed-Tasks {
margin-top: 15px;
}
.Task {
background: #FFFFFF;
padding: 5px 10px;
display: flex;
align-items: center;
justify-content: space-between;
}
.Task-Operations {
display: flex;
align-items: center;
}
.Operation {
height: 20px;
margin-left: 10px;
cursor: pointer;
}
.Done {
text-decoration: line-through;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>To-Do List</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<div class="Header">
<p class="Heading">TO-DO LIST</p>
</div>
<div class="Tasks-Space">
<div class="Add-Task">
<input type="text" placeholder="Enter your task here" class="Add-Task-Input">
<button class="Add-Task-Button">Add Task</button>
</div>
<p class="Tasks-Space-Heading">Pending Tasks</p>
<div class="Pending-Tasks">
<div class="Task">
<p class="Task-Text">Make a pie</p>
<div class="Task-Operations">
<img src="./Tick.png" alt="Done" class="Operation Tick">
<img src="./Cross.png" alt="Delete" class="Operation Cross">
</div>
</div>
<div class="Task">
<p class="Task-Text">Play Minecraft</p>
<div class="Task-Operations">
<img src="./Tick.png" alt="Done" class="Operation Tick">
<img src="./Cross.png" alt="Delete" class="Operation Cross">
</div>
</div>
</div>
<p class="Tasks-Space-Heading">Completed Tasks</p>
<div class="Completed-Tasks"></div>
</div>
<script src="./main.js"></script>
</body>
</html>
Try using this code
// Create a "close" button and append it to each list item
var myNodelist = document.getElementsByTagName("LI");
var i;
for (i = 0; i < myNodelist.length; i++) {
var span = document.createElement("SPAN");
var txt = document.createTextNode("\u00D7");
span.className = "close";
span.appendChild(txt);
myNodelist[i].appendChild(span);
}
// Click on a close button to hide the current list item
var close = document.getElementsByClassName("close");
var i;
for (i = 0; i < close.length; i++) {
close[i].onclick = function(data) {
var div = this.parentElement;
div.style.display = "none";
var data = div.innerText;
var list = document.getElementById("list");;
var firstname = div.value;
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(data));
list.appendChild(entry);
}
}
// Add a "checked" symbol when clicking on a list item
var list = document.querySelector('ul');
list.addEventListener('click', function(ev) {
if (ev.target.tagName === 'LI') {
ev.target.classList.toggle('checked');
}
}, false);
// Create a new list item when clicking on the "Add" button
function newElement() {
var li = document.createElement("li");
var inputValue = document.getElementById("myInput").value;
var t = document.createTextNode(inputValue);
li.appendChild(t);
if (inputValue === '') {
alert("You must write something!");
} else {
document.getElementById("myUL").appendChild(li);
}
document.getElementById("myInput").value = "";
var span = document.createElement("SPAN");
var txt = document.createTextNode("\u00D7");
span.className = "close";
span.appendChild(txt);
li.appendChild(span);
for (i = 0; i < close.length; i++) {
close[i].onclick = function() {
var div = this.parentElement;
div.style.display = "none";
}
}
}
body {
margin: 0;
min-width: 250px;
font-family: arial;
}
/* Include the padding and border in an element's total width and height */
* {
box-sizing: border-box;
}
/* Remove margins and padding from the list */
ul {
margin: 0;
padding: 0;
}
/* Style the list items */
ul li {
cursor: pointer;
position: relative;
padding: 12px 8px 12px 40px;
list-style-type: none;
font-size: 18px;
transition: 0.2s;
border-bottom: 1px solid #eee;
margin-top: -1px;
/* make the list items unselectable */
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
/* When clicked on, add a background color and strike out text */
ul li.checked {
background: #888;
color: #fff;
text-decoration: line-through;
}
/* Add a "checked" mark when clicked on */
ul li.checked::before {
content: '';
position: absolute;
border-color: #fff;
border-style: solid;
border-width: 0 2px 2px 0;
top: 10px;
left: 16px;
transform: rotate(45deg);
height: 15px;
width: 7px;
}
/* Style the close button */
.close {
position: absolute;
right: 0;
top: 0;
padding: 12px 16px 12px 16px;
}
.close:hover {
background-color: #f44336;
color: white;
}
/* Style the header */
.header {
background-color: #f44336;
padding: 30px 40px;
color: white;
text-align: center;
}
/* Clear floats after the header */
.header:after {
content: "";
display: table;
clear: both;
}
/* Style the input */
input {
margin: 0;
border: none;
border-radius: 0;
width: 75%;
padding: 10px;
float: left;
font-size: 16px;
}
input[type=text] {
outline: 0;
background: #eee;
border: 0;
transition: all .2s;
}
input[type=text]:focus {
background: #fff;
box-shadow: 0 3px 1px -2px rgba(0, 0, 0, 0.2), 0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 1px 5px 0 rgba(0, 0, 0, 0.12);}
/* Style the "Add" button */
.addBtn {
padding: 10px;
width: 25%;
background: #d9d9d9;
color: #555;
float: left;
text-align: center;
font-size: 16px;
cursor: pointer;
transition: 0.3s;
border-radius: 0;
}
.addBtn:hover {
background-color: #bbb;
}
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
<div id="myDIV" class="header">
<h2 style="margin:5px">My To Do List</h2>
<input type="text" id="myInput" placeholder="Title..." autocomplete="off">
<span onclick="newElement()" class="addBtn">Add</span>
</div>
<ul id="myUL">
<li>Hit the gym</li>
<li>Pay bills</li>
<li>Meet George</li>
<li>Buy eggs</li>
<li>Read a book</li>
<li>Organize office</li>
</ul>
<p style="padding-left: 30px;">Completed Tasks</p>
<ul id="list"></ul>
I have an search bar which is working perfectly.
But getting an issue. I want only 5 results to be vsible at a time and other results should be seen by sliding from the slider.
For example if it contains 10 results. Then is shoould show ony 5 on searching and to see other user can sllide from the slidebar....
here is my code
function filterFunction() {
let isInputAvail = false;
var input, filter, ul, li, a, i;
input = document.getElementById("myInput");
filter = input.value.toLowerCase();
if (filter.length > 0) {
document.getElementById("myDropdown").classList.add("show");
} else {
document.getElementById("myDropdown").classList.remove("show");
}
div = document.getElementById("myDropdown");
a = div.getElementsByTagName("a");
for (i = 0; i < a.length; i++) {
txtValue = a[i].innerText;
if (txtValue.toLowerCase().indexOf(filter) > -1) {
isInputAvail = true;
a[i].style.display = "block";
} else {
a[i].style.display = "none";
}
}
if (!isInputAvail) {
document.getElementById("noMatches").classList.add('show');
} else {
document.getElementById("noMatches").classList.remove('show');
}
}
.div {
display: none;
}
.dropbtn {
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
border-radius: 25px;
}
#myInput {
box-sizing: border-box;
background-position: 14px 12px;
background-repeat: no-repeat;
font-size: 16px;
padding: 14px 20px 12px 45px;
border: 5px solid #ddd;
border-radius: 25px;
}
#myInput:focus {
outline: 4px solid #f2f2f2;
border-color: #171313;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f6f6f6;
min-width: 230px;
overflow: auto;
border: none;
z-index: 1;
border-radius: 25px;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown a:hover {
background-color: #ddd;
}
.show {
display: block;
}
<div class="dropdown">
<input type="text" class="dropbtn" placeholder="Search Here..." id="myInput" onInput="filterFunction()">
<div id="myDropdown" class="dropdown-content">
Result 1
Result 2
Result 3
Result 4
Result 5
Result 6
Result 7
Result 8
Result 9
Result 10
Result 11
Result 12
Result 13
Result 14
Result 15
</div>
<div id="noMatches" class="dropdown-content">
No Matches
</div>
</div>
Here i want that when i write result then all the matching result is shown but that show a huge list. I want to make it to show ony 5 result and there should be a slidebar at right side from which on sliding other results can be seen.
Hope you got my point.
Thanks in advance.
Check out this snippet:
function filterFunction() {
let isInputAvail = false;
var input, filter, ul, li, a, i;
input = document.getElementById("myInput");
filter = input.value.toLowerCase();
if (filter.length > 0) {
document.getElementById("myDropdown").classList.add("show");
} else {
document.getElementById("myDropdown").classList.remove("show");
}
div = document.getElementById("myDropdown");
a = div.getElementsByTagName("a");
for (i = 0; i < a.length; i++) {
txtValue = a[i].innerText;
if (txtValue.toLowerCase().indexOf(filter) > -1) {
isInputAvail = true;
a[i].style.display = "block";
} else {
a[i].style.display = "none";
}
}
if (!isInputAvail) {
document.getElementById("noMatches").classList.add('show');
} else {
document.getElementById("noMatches").classList.remove('show');
}
}
.div {
display: none;
}
.dropbtn {
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
border-radius: 25px;
}
#myInput {
box-sizing: border-box;
background-position: 14px 12px;
background-repeat: no-repeat;
font-size: 16px;
padding: 14px 20px 12px 45px;
border: 5px solid #ddd;
border-radius: 25px;
}
#myInput:focus {
outline: 4px solid #f2f2f2;
border-color: #171313;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
max-height: 215px;
display: none;
position: absolute;
background-color: #f6f6f6;
min-width: 230px;
overflow-y: scroll;
border: none;
z-index: 1;
border-radius: 25px;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown a:hover {
background-color: #ddd;
}
.show {
display: block;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test</title>
</head>
<body>
<div class="dropdown">
<input type="text" class="dropbtn" placeholder="Search Here..." id="myInput" onInput="filterFunction()">
<div id="myDropdown" class="dropdown-content">
Result 1
Result 2
Result 3
Result 4
Result 5
Result 6
Result 7
Result 8
Result 9
Result 10
Result 11
Result 12
Result 13
Result 14
Result 15
</div>
<div id="noMatches" class="dropdown-content">
No Matches
</div>
</div>
</body>
</html>
I have limited maximum height of .dropdown-content using max-height property and set vertical overflow to scroll using overflow-y: scroll;. Removed overflow: auto from .dropdown-content.
Don't use IDs, programming should be writing reusable code.
To show the dropdowns or to switch the list/no-matches, use two classes on the parent element ("hasvalue" and "nomatch"), the rest is all pure CSS and the :focus selector
Use CSS max-height to limit the height of your overflow element
UI/UX tip: half-cut the last list word, to additionally give the user a clue that there's more items in the scrollable element.
function dropdown(EL) {
const EL_input = EL.querySelector(".dropdown-input");
const ELS_li = EL.querySelectorAll(".dropdown-box--list a");
const filter = () => {
const val = EL_input.value.trim().toLowerCase();
const fil = [...ELS_li].filter(el => {
const match = el.textContent.trim().toLowerCase().includes(val);
el.classList.toggle("hide", !match);
return match;
});
EL.classList.toggle("hasvalue", val.length);
EL.classList.toggle("nomatch", val.length && !fil.length);
};
EL_input.addEventListener("input", filter);
EL_input.addEventListener("focus", filter);
ELS_li.forEach(el => el.addEventListener("mousedown", () => {
EL_input.value = el.textContent.trim()
}));
}
document.querySelectorAll(".dropdown").forEach(el => dropdown(el));
/* QuickReset */ * {margin: 0; box-sizing: border-box;}
/* DROPDOWN COMPONENT */
.dropdown {
--item-height: 30px;
--visible: 5;
font-family: sans-serif;
position: relative;
display: inline-block;
}
.dropdown-input {
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
font-size: 16px;
padding: 15px 20px;
border: 5px solid #ddd;
border-radius: 25px;
background: #fff;
}
.dropdown-input:focus {
outline: none;
border-color: #000;
}
.dropdown.hasvalue .dropdown-input:focus {
border-bottom: 1px solid #ddd;
border-radius: 25px 25px 0 0;
}
.dropdown-box {
display: none;
position: absolute;
top: 100%;
z-index: 1;
min-width: 100%;
overflow: auto;
border-radius: 0 0 10px 10px;
max-height: calc(var(--item-height) * var(--visible));
border: 5px solid #000;
border-top: 0;
}
.dropdown.hasvalue .dropdown-input:focus~.dropdown-box--list {
display: block;
}
.dropdown.nomatch .dropdown-input:focus~.dropdown-box--list {
display: none;
}
.dropdown.nomatch .dropdown-input:focus~.dropdown-box--nomatch {
display: block !important;
}
.dropdown-box a {
display: flex;
align-items: center;
padding: 7px 20px;
min-height: var(--item-height);
color: black;
text-decoration: none;
transition: background 0.24s;
}
.dropdown-box a.hide {
display: none;
}
.dropdown-box a:hover {
background-color: #acf;
}
.dropdown-box::-webkit-scrollbar {
width: 10px;
height: 10px;
}
.dropdown-box::-webkit-scrollbar-track {
background: transparent;
border-radius: 10px;
}
.dropdown-box::-webkit-scrollbar-thumb {
background-color: #000;
border-radius: 10px;
}
<div class="dropdown">
<input type="text" class="dropdown-input" autocomplete="off" placeholder="🔍︎ Search...">
<div class="dropdown-box dropdown-box--list">
Result 1
Result 2
Result 3
Result 4
Result 5
Result 6
Result 7
Result 8
Result 9
Result 10
Result 11
Result 12
Result 13
Result 14
Result 15
</div>
<div class="dropdown-box dropdown-box--nomatch">
<i>No Matches</i>
</div>
</div>
<div class="dropdown">
<input type="text" class="dropdown-input" autocomplete="off" placeholder="🔍︎ Yet another...">
<div class="dropdown-box dropdown-box--list">
Lorem
Ipsum
Dolor sit amet
Lorem ut florem
</div>
<div class="dropdown-box dropdown-box--nomatch">
<i>No Matches</i>
</div>
</div>
I am brand new to javascript, but I have a little bit of knowledge in using HTML. The problem I am facing with my website is I created an image gallery, everything works as expected, but I cannot seem to get the content to stay inside the webpage. Here is an image of what my problem looks like: https://imgur.com/RkhF0Ka
I have already tried setting the wrapper and body height to 100%, I have tried editing the CSS file with different display settings (e.x. absolute, relative, etc), I have tried creating a wrapper inside the article itself. None of these worked. I just want to get rid of the blocks in the webpage background and have all my content on the same page. Any help would be greatly appreciated.
My HTML Code:
<!-- Title of website and page -->
<title>....:: Gallery</title>
<!-- Added variable width character encoding -->
<meta charset="utf-8">
<!-- Compatiblility for IE and Chrome -->
<!--[if IE]><meta http-equiv='X-UA-Compatible'
content='IE=edge,chrome=1'><![endif]-->
<!-- Link to external CSS style sheet -->
<link href="pps.css" rel="stylesheet">
<!--Added tablet and mobile scaling-->
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<!-- Added older browser compatibility-->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js">
</script>
<![endif]-->
<!-- Script element to link to modernizer -->
<script src="modernizr.custom.05819.js"></script>
</head>
<body>
<!-- Added a wrapper to ensure the whole page shares the same CSS style-- >
<div id="wrapper">
<!-- Document header -->
<header>
<h1>....</h1>
<!-- Added a div class to header for image map -->
<div id="header">
<!--Added image map to HTML document-->
<map name="imgmap" id="imgmap">
<area href="https://..../" shape="rect"
coords="30,25,345,174" alt=".... Logo">
<area href="https://...../" shape="rect"
coords="500,25,845,174" alt="....">
</map>
<img src="...." usemap="#imgmap" alt="...." width="1020" height="200">
</div>
</header>
<nav> <!-- Created navigation bar and an unordered list for website
pages -->
<ul> <!-- Created button class for navigation menu-->
<li><a class="button" href="index.html">Home</a></li>
<li><a class="button" href="...s.html">...s</a></li>
<li><a class="button" href=".....html">...</a></li>
<li><a class="button" href="....html">...</a></li>
<li><a class="button" href="....html">....</a></li>
<li><a class="button" href="....html">....</a></li>
<li><a class="button" href="....html">....</a></li>
</ul>
</nav>
<!-- Added a div class for the hero image of Gallery -->
<div id="galleryhero"></div>
<!-- main body of document -->
<main>
<!-- h2 element for webpage -->
<h2>Gallery</h2>
<!-- Added paragraph to document -->
<p><span class=".....">...</span> ....</p> <br>
<h2>Images</h2>
<!-- Create image gallery layout -->
<article>
<div id="leftarrow"> <!-- create id for left arrow -->
<p><</p>
<figure id="fig2"> <!-- create id for figure 2 -->
<img src="images" alt="fig2" width="360" height="202" />
</figure>
<figure id="fig3">
<img src="images" alt="fig3" width="480" height="270" />
</figure>
<figure id="fig4">
<img src="images" alt="fig4" width="360" height="202" />
</figure>
<div id="rightarrow"> <!-- create id for right arrow -->
<p>></p>
<div id="fiveButton"> <!-- create id for fiveButton -->
<p>Show more images</p>
</div>
</article>
<script src="photos.js"></script> <!-- create script src to load the
file photos.js -->
<br> <!-- Break element -->
<!-- Added a footer to document -->
<footer>
<div id="footer">
<!-- Added an unorderedlist for footer element -->
<ul>
<li>.....</li>
<li>.....</li>
<li>.....<li>
<li>.....</li>
<li>.....</li>
<li>.....</li>
<li>.....</li>
</ul>
</div>
<!-- Added a copyright mark and fake e-mail address -->
Copyright © 2019 ..... <br>
....com
</footer>
</main>
</div>
</body>
</html>
My CSS Code:
/* Document body configurations */
body { background-color: #fffff0;
background: url("bg.jpg"); /* Configured background url to a root-
absolute url */
height: 100%;
color: #000000;
font-family: Verdana, Ariel, Helvetica; }
/* Document h1 configurations */
h1 { background-color: #FFFFFF;
color: #000000;
font-size: 0.1px;
font-family: Georgia, "Times New Roman", Palatino;
text-indent: 100%;
white-space: nowrap;
overflow: hidden; }
/* Document header configurations */
header {height: 205px;
background-color: #FFFFFF;
background: url("ppheader.gif");
margin-bottom: 0;
padding-bottom: 50px;
border-style: solid;
border-color: #000000;
color: #000000;
font-family: Georgia, "Times New Roman", Palatino; }
/* Document h2 configurations */
h2 { background-color: #fffff0;
color: #e65c00;
text-align: center;
font-family: Georgia, "Times New Roman", Palatino; }
/* Document h3 configurations */
h3 { color: #000033;
float:left; }
/* Document main body configurations */
main { padding-left: 20px;
padding-right: 20px;
display: block;
background-color: #fffff0;
margin-left: 1px;
padding-bottom: 300px;
padding-top: 1px; }
/* Document configurations for buttons */
.button { display: block;
width: 10em;
padding: 1em;
color: #FFFFFF;
background-color: #000000;
font-family: Verdana, Helvetica, Arial;
font-size: 1em;
font-weight: bold;
border: 1px solid white;
margin: 0;
text-decoration: none; }
/* Document image gallery configurations */
figure { display: inline-block;
list-style-type: none;
width: 269px;
height: 448px; }
/* Added a caption for videos */
figure figcaption {width: 269px;
padding-bottom: 10px;
margin: 0;
background-color: #f4f4f0;
text-align: center;
font-weight: bold;
font-style: italic;
font-family: Helvetica, serif; }
/* Document button configurations */
.button:link { color: #FFFFFF; }
.button:visited { color: #ffe066; }
.button:hover { color: #990000; }
/* Document navigation bar configurations */
nav ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #333;
}
nav li {
float: left;
border-right: 1px solid black;
}
nav li a {
display: block;
color: white;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}
/* Document header, navigation, main body, and footer display
configurations */
header, nav, main, footer { display: block; }
/* Document table configurations */
table { margin: auto;
border: 1px solid #982e01;
width: 90%;
border-collapse: collapse; }
td { text-align: center; }
th, td { padding: 5px;
border: 1px solid #982e01; }
/* Document paragraph configurations */
#text { text-align: left; }
tr:first-of-type { background-color: #000000;
color: #FFFFFF; }
tr:nth-of-type(even) { background-color: #fffecc; }
dt { color: #000033;
font-weight: bold; }
.paulpaintservice { color: #982e01;
font-size: 1.2em; }
/* Document logo configurations */
.logo { color: #FFFFFF;
font-size: 3em; }
/* Document footer configurations */
footer { font-size: .70em;
font-style: italic;
text-align: center;
padding: 10px;
margin-top: 100px;
background-color: #fffff0;
margin-left: 5px; }
#footer ul { text-align: center; list-style-type: none; }
#footer li { display: inline;
background-color: #fffff0; }
#footer a { padding: 2px 10px; }
/* Document box style configurations */
* { box-sizing: border-box;}
/* Document wrapper configurations that create a box model for the
website */
#wrapper { background-color: #000000;
margin-left: auto;
margin-right: auto;
height: 100%;
min-width: 700px;
max-width: 1024px;
box-shadow: 5px 5px 5px #1e1e1e; }
/* Document hero image configurations for the home, services, gallery,
about, and appointment pages */
#homehero { height: 300px;
background-image: url("hsunset3.jpg");
background-size: 100% 100%;
background-repeat: no-repeat;
margin-left: 1px; }
#servicehero { height: 300px;
background-image: url("hsunset2.jpg");
background-size: 100% 100%;
background-repeat: no-repeat;
margin-left: 1px; }
#galleryhero { height: 300px;
background-image: url("hsunset.jpg");
background-size: 100% 100%;
background-repeat: no-repeat;
margin-left: 1px; }
#abouthero { height: 300px;
background-image: url("hevening.jpg");
background-size: 100% 100%;
background-repeat: no-repeat;
margin-left: 1px; }
#projecthero { height: 300px;
background-image: url("hocean.jpg");
background-size: 100% 100%;
background-repeat: no-repeat;
margin-left: 1px; }
#securityhero { height: 300px;
background-image: url("hfield.jpg");
background-size: 100% 100%;
background-repeat: no-repeat;
margin-left: 1px; }
#appointmenthero { height: 300px;
background-image: url("hvalley.jpg");
background-size: 100% 100%;
background-repeat: no-repeat;
margin-left: 1px; }
/* Configure pc.gif to float to the left on "About" page */
#pc { float: left;
margin: 0 16px 16px 0;
border: 2px ridge black;
border-radius: 5px;
background: #FFFFFF;}
/* Document "About" page paragraph configurations */
p { text-align: left;
font-size: 1.2em; }
/* Document "Gallery" configurations */
#gallery { position: relative; }
#gallery ul { width: fill; list-style-type: none; }
#gallery img { border: 1px solid black;
margin: 10px; }
#gallery a { text-decoration: none; color: #e65c00; font-style: italic;
font-family: Helvetica;
font-weight: bold; }
#gallery span { display: none; }
#gallery li { display: inline-block; }
#gallery a:hover span {display: block;
position: absolute;
left: 300px;
top: 0;
text-align: center;
text-shadow: 2px 2px 3px #000000; }
/* Document navigation configurations */
nav a { text-decoration: none; }
nav a:link { color: #FFFFFF; }
nav a:visited { color: #ffe066; }
nav a:hover { color: #FFFFFF; }
nav ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #333;
}
nav li {
float: left;
border-right: 1px solid black;
}
nav li a {
display: block;
color: white;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}
/* Document header, navigation, main body, and footer display
configurations */
header, nav, main, footer { display: block; }
label { float: left;
width: 8em;
display: block;
padding-right: 1em; }
/* Document contact form configurations */
input, textarea { margin-bottom: 1em;
margin-top: 1.2em;
display: block; }
/* Configure <form> */
#mySubmit { margin-left: 10em; }
#mobile { display: none; }
#desktop { display: inline; }
/* apply a natural box layout model to all elements */
* {
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
/* reset rules */
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
display: block;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
a:link, a:visited {
text-decoration: none;
color: inherit;
}
a:hover {
text-decoration: none;
color: inherit;
}
a:active {
text-decoration: none;
color: inherit;
}
/* main content */
article {
background: white;
position: relative;
}
article h2 {
font-size: 1.2em;
font-weight: bold;
text-align: left;
margin: 0 0 10px 51px;
}
#leftarrow, #rightarrow {
background: #696565;
color: white;
position: absolute;
z-index: 30;
text-align: center;
height: 135px;
width: 40px;
top: 67px;
}
article div:hover {
cursor: default;
}
#leftarrow {
left: 0;
}
#rightarrow {
right: 0;
}
#fiveButton {
display: block;
width: 100%;
position: absolute;
top: 290px;
color: white;
text-align: center;
}
#fiveButton p {
width: 20%;
margin: 0 auto;
line-height: 2em;
background: #696565;
}
#leftarrow p, #rightarrow p {
position: relative;
top: 50%;
margin-top: -0.5em;
}
figure {
position: absolute;
-webkit-box-shadow: 10px 0px 5px rgb(50, 50, 50),
-10px 0px 5px rgb(50, 50, 50);
-moz-box-shadow: 10px 0px 5px rgb(50, 50, 50),
-10px 0px 5px rgb(50, 50, 50);
box-shadow: 10px 0px 5px rgb(50, 50, 50),
-10px 0px 5px rgb(50, 50, 50);
}
#fig2 {
z-index: 10;
left: 13%;
top: 34px;
}
#fig3 {
z-index: 20;
left: 50%;
margin-left: -240px;
top: 0;
}
#fig4 {
z-index: 10;
right: 13%;
top: 34px;
}
/* Document configurations for mobile devices */
#media only screen and (max-width: 1024px)
/* Document body configurations */
{
body { margin: 0;
padding: 0;
background-image: none; }
/* Document wrapper configurations */
#wrapper { min-width: 0;
margin: 0;
box-shadow: none; }
/* Document h1 configurations */
h1 { margin: 0; }
/* Document navigation configurations */
nav { float: none;
width: auto;
padding: 0.5em; }
nav li { display: inline-block; }
nav a { padding: 1em; }
/* Document main body configurations */
main { padding: 1em;
margin-left: 0;
font-size: 90%; }
/* Document footer configurations */
footer { margin: 0; }
/* Document hero image configurations */
#homehero { margin-left: 0; }
#servicehero { margin-left: 0; }
#galleryhero { margin-left: 0; }
#abouthero { margin-left: 0; }
#appointmenthero { margin-left: 0; }
#projecthero { margin-left: 0; }
#securityhero { margin-left: 0; }
/* Document logo configurations */
.logo { margin-left: 0; }
}
/* Document configurations for mobile devices */
#media only screen and (max-width: 768px) {
/* Document h1 configurations */
h1 { height: 100%;
font-size: 1.5em;
padding-left: 0.3em;
background: none; }
/* Document navigation configurations */
nav { padding: 0; }
nav a { display: block;
padding: 0.2em;
font-size: 1.3em;
border-bottom: 1px;
border-color: #330000; }
nav ul { margin : 0;
padding: 0; }
nav li { display: block;
margin: 0;
padding: 0; }
/* Document button configurations */
.button { width: auto; }
/* Document main body configurations */
main { padding-top: 0.1em;
padding-right: 0.6em;
padding-bottom: 0.1em;
padding-left: 0.4em; }
/* Document hero image configurations */
#homehero { display: none; }
#servicehero { display: none; }
#galleryhero { display: none; }
#abouthero { display: none; }
#appointmenthero { display: none; }
#projecthero { display: none; }
#securityhero { display: none; }
/* Document footer configurations */
footer { padding: 0; }
/* Document mobile, desktop, and header display options configurations */
#mobile { display: inline; }
/* Disable desktop mode while on mobile device */
#desktop { display: none; }
/* Disable header image while on mobile device */
#header { display: none; }
}
Here is my image gallery JS code:
"use strict"; // interpret document contents in JavaScript strict mode
/* global variables */
var photoOrder = [1,2,3,4,5];
var figureCount = 3;
/* Add src values to img elements based on order specified in photoOrder
array */
function populateFigures() {
var filename;
var currentFig;
if (figureCount === 3) {
//Add for loop with 3 interations and increments i by 1 after each loop
for (var i = 1; i < 4; i++) {
filename = "images/IMG_0" + photoOrder[i] + "sm.jpg";
currentFig = document.getElementsByTagName("img")[i - 1];
currentFig.src = filename;
}
//Else statement and for loop with 6 iterations
} else {
for (var i = 0; i < 5; i++) {
filename = "images/IMG_0" + photoOrder[i] + "sm.jpg";
currentFig = document.getElementsByTagName("img")[i];
currentFig.src = filename;
}
}
}
/* shift all images one figure to the left, and change values in photoOrder
array to match */
rightArrow() {
for (var i = 0; i < 5; i++) {
after each cycle
if ((photoOrder[i] + 1) === 6) {
photoOrder[i] = 1;
} else {
photoOrder[i] += 1;
}
populateFigures(); //Call populateFigures()
}
}
/* shift all images one figure to the right, and change values in photoOrder
array to match */
function leftArrow() {
for (var i = 0; i < 5; i++) {
if ((photoOrder[i] - 1) === 0) {
with index i minus 1 is equal to the value of 0
photoOrder[i] = 5;
} else {
photoOrder[i] -= 1;
}
populateFigures(); //Call populateFigures()
}
}
/* switch to 3-image layout */
function previewThree() {
var articleEl = document.getElementsByTagName("article")[0];
var numberButton = document.querySelector("#fiveButton p");
/* Remove the 1st and 5th figure elements */
articleEl.removeChild(document.getElementById("fig1"));
articleEl.removeChild(document.getElementById("fig5"));
figureCount = 3;
numberButton.innerHTML = "Show more images";
if (numberButton.addEventListener) {
numberButton.removeEventListener("click", previewThree,
false);
numberButton.addEventListener("click", previewFive, false);
} else if (numberButton.attachEvent) {
numberButton.detachEvent("onclick", previewThree);
numberButton.attachEvent("onclick", previewFive);
}
}
/* switch to 5-image layout */
function previewFive() {
var articleEl = document.getElementsByTagName("article")[0];
//Create figure and img elements for 5th image
var lastFigure = document.createElement("figure");
//Configure settings for 5th figure
lastFigure.id = "fig5";
lastFigure.style.zIndex = "5";
lastFigure.style.position = "absolute";
lastFigure.style.right = "45px";
lastFigure.style.top = "67px";
var lastImage = document.createElement("img");
lastImage.width = "240";
lastImage.height = "135";
lastFigure.appendChild(lastImage);
articleEl.appendChild(lastFigure);
//clone figure element for fifth image and edit to be first image
var firstFigure = lastFigure.cloneNode(true);
/* Change the id value for the firstFigure node from fig5 and the value
cloned from the lastFigure node to fig1, remove cloned value for the right
CSS style and specify a new value for the left CSS style */
firstFigure.id = "fig1";
firstFigure.style.right = "";
string
firstFigure.style.left = "45px";
//Use the appendChild() method to add the firstFigure node to document tree
//articleEl.appendChild(firstFigure);
articleEl.insertBefore(lastFigure,
document.getElementById("rightarrow"));
/* Insert the firstFigure node before the existing element with the id
value
fig2 */
articleEl.insertBefore(firstFigure,
document.getElementById("fig2"));
//Change from 3 images to 5 when user switches to viewing 5 photos
figureCount = 5; //Assign an image for each img element
//Add appropriate src values to two new img elements
document.getElementsByTagName("img")[0].src = "images/IMG_0" + photoOrder[0]
+ "sm.jpg";
document.getElementsByTagName("img")[4].src = "images/IMG_0" + photoOrder[4]
+ "sm.jpg";
//change button to hide extra images
var numberButton = document.querySelector("#fiveButton p"); //Assign var
numberButton value to the selector element with id #fiveButton p
numberButton.innerHTML = "Show fewer images"; //Assign the innerHTML
numberButton to the attribute show fewer images
if (numberButton.addEventListener) {
numberButton.removeEventListener("click", previewFive,
false); //Remove 5-image view
numberButton.addEventListener("click", previewThree,
false);
} else if (numberButton.attachEvent) { /* Add else-if statement to switch
between a preview of 5 or 3 images */
numberButton.detachEvent("onclick", previewFive);
numberButton.attachEvent("onclick", previewThree);
}
}
/* create event listeners for left arrow, right arrow, and
center figure element
*/
function createEventListeners() {
var leftarrow = document.getElementById("leftarrow"); //create var named
leftarrow and assign value to the element with the id value leftarrow
//if/else statement to create the event listener for the left navigation
arrow
if (leftarrow.addEventListener) {
leftarrow.addEventListener("click", leftArrow, false);
} else if (leftarrow.attachEvent) {
leftarrow.attachEvent("onclick", leftArrow);
}
/* create a variable and assign an event listener for the right navigation
arrow */
var rightarrow = document.getElementById("rightarrow"); //create var named
rightarrow and assign value to the element with the id value rightarrow
if (rightarrow.addEventListener) {
rightarrow.addEventListener("click", rightArrow, false);
} else if (rightarrow.attachEvent) {
rightarrow.attachEvent("onclick", rightArrow);
}
//Add event listener for the third img element in the document that has index
value 2
var mainFig = document.getElementsByTagName("img")[1]; //Create var variable
mainFig and assign value to the second image element with the index value of
1
//Add if-else statement to create the event listener to call zoomFig() when
user clicks the center image
if (mainFig.addEventListener) { //Add if statement to not zoom into image
if it is not clicked
mainFig.addEventListener("click", zoomFig, false);
} else if (mainFig.attachEvent) { //Add else-if statement to zoom into image
when clicked
mainFig.attachEvent("onclick", zoomFig);
}
var showAllButton = document.querySelector("#fiveButton p"); //Assign var
showAllButton value to the selector element with id #fiveButton p
if (showAllButton.addEventListener) {
showAllButton.addEventListener("click", previewFive, false);
} else if (showAllButton.attachEvent) {
showAllButton.attachEvent("onclick", previewFive);
}
}
/* open center figure in separate window */
function zoomFig() {
var propertyWidth = 960; //Assign var propertyWidth value to 960px
var propertyHeight = 600; //Assign var propertyHeight value to 600px
var winLeft = ((screen.width - propertyWidth) / 2); // Create var named
winLeft and start with the width of the existing browser window minus the
width of the new browser window, divided by two
var winTop = ((screen.height - propertyHeight) / 2); // Create var named
winTop and start with the height of the existing browser window minus the
width of the new browser window, divided by two
var winOptions = "width=960,height=600"; //Create var named winOptions and
assign to the width of 960px and height of 600px
winOptions += ",left=" + winLeft; //Create an option string for the
window.open() method that incorporates the calculated values for the left of
window
winOptions += ",top=" + winTop; //Create an option string for the
window.open() method that incorporates the calculated values for the top of
window
var zoomWindow = window.open("zoom.htm", "zoomwin", "width=960,height=600");
//Create variable named zoomWindow and assign to the window created by
window.open to display contents of zoom html file
zoomWindow.focus(); //Make the external photo gallery window the active
window
}
/* create event listeners and populate image elements */
function setUpPage() { //Call function
createEventListeners(); //Call function
populateFigures(); //Call function
}
/* run setUpPage() function when page finishes loading */
if (window.addEventListener) {
window.addEventListener("load", setUpPage, false);
} else if (window.attachEvent) {
window.attachEvent("onload", setUpPage);
}
Another bizarre thing that happened was that the logo/header image loads at first, then it immediately switches to one of the image gallery photos. I could not figure out how to fix that...
I'm using a Google visualization query to pull column headings from this spreadsheet. Currently I must include the row and column indexes for each cell I want in the menu. What I'd like is a script that'll populate this menu dynamically with data from the cells in row 1 of the spreadsheet. In other words, make the menu as big or as small as what exists on the spreadsheet.
I believe I need something like the following, but I'm unsure how to implement it. Perhaps I need server side script (GAS) to accomplish this??
<select>
for (var i = 0; i < data.length; ++i) {
<option>!= data[i] </option>
}
</select>
I've found plenty of documentation to accomplish this using Google's HTMLService, but I need this menu to be hosted using a different service.
Any help would be greatly appreciated. Thanks!
My current code follows...
google.load('visualization', '1', {'packages':['corechart']});
google.setOnLoadCallback(ValIDS);
function ValIDS() {
var queryValIDS = new google.visualization.Query('https://docs.google.com/spreadsheet/ccc?key=1HpHMfoEnPgESb2XPVCgb7XyGwRAvrq3EoQj4WHj4vhA&sheet=QUERY2');
queryValIDS.send(handleQueryValIDResponse);
}
function handleQueryValIDResponse(response) {
if (response.isError()) {
alert('Error in ID Validation Query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var datatable = response.getDataTable();
var cat1 = datatable.getValue(0,0);
var cat2 = datatable.getValue(0,1);
var cat3 = datatable.getValue(0,2);
var cat4 = datatable.getValue(0,3);
var cat5 = datatable.getValue(0,4);
var cat6 = datatable.getValue(0,5);
var cat7 = datatable.getValue(0,6);
var cat8 = datatable.getValue(0,7);
var cat9 = datatable.getValue(0,8);
var cat10 = datatable.getValue(0,9);
document.getElementById('cat1').innerHTML = cat1;
document.getElementById('cat2').innerHTML = cat2;
document.getElementById('cat3').innerHTML = cat3;
document.getElementById('cat4').innerHTML = cat4;
document.getElementById('cat5').innerHTML = cat5;
document.getElementById('cat6').innerHTML = cat6;
document.getElementById('cat7').innerHTML = cat7;
document.getElementById('cat8').innerHTML = cat8;
document.getElementById('cat9').innerHTML = cat9;
document.getElementById('cat10').innerHTML = cat10;
}
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
.dropbtn {
background-color: #4CAF50;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}
.dropbtn:hover, .dropbtn:focus {
background-color: #3e8e41;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
overflow: auto;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown a:hover {background-color: #f1f1f1}
.show {display:block;}
.dropbtn {
background-color: #4CAF50;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}
.dropbtn:hover, .dropbtn:focus {
background-color: #3e8e41;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
overflow: auto;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown a:hover {background-color: #f1f1f1}
.show {display:block;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">Dropdown</button>
<div id="myDropdown" class="dropdown-content">
<div id="cat1"></div>
<div id="cat2"></div>
<div id="cat3"></div>
<div id="cat4"></div>
<div id="cat5"></div>
<div id="cat6"></div>
<div id="cat7"></div>
<div id="cat8"></div>
<div id="cat9"></div>
<div id="cat10"></div>
</div>
</div>
you can use client-side JavaScript to build the drop-down dynamically
using the data from the datatable
there are a number of ways, but this should accomplish what you need
you can use getNumberOfColumns rather than hard-coding each drop-down item
this will allow additional columns to be added to the spreadsheet,
without having to change the code / html
for (var i = 0; i < datatable.getNumberOfColumns(); i++) {
var ddItem = document.getElementById('myDropdown').appendChild(document.createElement('A'));
ddItem.href = '#';
var ddItemContent = ddItem.appendChild(document.createElement('SPAN'));
ddItemContent.id = 'cat' + (i + 1);
ddItemContent.innerHTML = datatable.getValue(0, i);
}
(i + 1) was used on the id above,
just so the id would be the same as what you had hard-coded
since anchors (<a>) are inline elements,
a <span> was used instead of <div>
you may not even need id, or the SPAN for that matter,
since the drop-down items are being created dynamically
see following working snippet...
google.load('visualization', '1', {'packages':['corechart']});
google.setOnLoadCallback(ValIDS);
function ValIDS() {
var queryValIDS = new google.visualization.Query('https://docs.google.com/spreadsheet/ccc?key=1HpHMfoEnPgESb2XPVCgb7XyGwRAvrq3EoQj4WHj4vhA&sheet=QUERY2');
queryValIDS.send(handleQueryValIDResponse);
}
function handleQueryValIDResponse(response) {
if (response.isError()) {
alert('Error in ID Validation Query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var datatable = response.getDataTable();
for (var i = 0; i < datatable.getNumberOfColumns(); i++) {
var ddItem = document.getElementById('myDropdown').appendChild(document.createElement('A'));
ddItem.href = '#';
var ddItemContent = ddItem.appendChild(document.createElement('SPAN'));
ddItemContent.id = 'cat' + (i + 1);
ddItemContent.innerHTML = datatable.getValue(0, i);
}
}
function myFunction() {
document.getElementById('myDropdown').classList.toggle('show');
}
window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName('dropdown-content');
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
.dropbtn {
background-color: #4CAF50;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}
.dropbtn:hover, .dropbtn:focus {
background-color: #3e8e41;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
overflow: auto;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown a:hover {background-color: #f1f1f1}
.show {display:block;}
.dropbtn {
background-color: #4CAF50;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}
.dropbtn:hover, .dropbtn:focus {
background-color: #3e8e41;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
overflow: auto;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown a:hover {background-color: #f1f1f1}
.show {display:block;}
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">Dropdown</button>
<div id="myDropdown" class="dropdown-content"></div>
</div>
EDIT
the getValue method takes two arguments
getValue(rowIndex, columnIndex)
both rowIndex and columnIndex are zero-based,
meaning the first cell value would be getValue(0, 0)
if you want to pull values from the first column of each row...
use i as rowIndex and 0 as columnIndex
for (var i = 0; i < datatable.getNumberOfRows(); i++) {
var test = datatable.getValue(i, 0);
}