I m trying to make a bookmark app in which when i type the name and address of a website they should appear underneath the form when i click submit button.Also when i click the delete button it should remove item not only from UI but also from local storage.And that s the problem.I have no problem deleting them from UI but when i reload the page they keep showing up.I know it s complicated but if someone s interested i would urge them to pay attention to Store class which deals with storage particulary deleteBookmarkFromStorage() method.
document.getElementById("myForm").addEventListener("submit", saveBookmark);
document.querySelector(".col-lg-12").addEventListener("click", function(e) {
const ui = new UI();
ui.deleteItem(e.target);
Store.deleteBookmarkFromStorage(e.target.parentElement);
ui.showAlert("You deleted a bookmark", "alert alert-success");
e.preventDefault();
});
class Bookmark {
constructor(siteName, siteUrl) {
this.siteName = siteName;
this.siteUrl = siteUrl;
}
}
class UI {
constructor() {
this.siteName = document.getElementById("siteName");
this.siteUrl = document.getElementById("siteUrl");
this.bookmarksResults = document.getElementById("bookmarksResults");
}
showAlert(message, className) {
const div = document.createElement("div");
div.appendChild(document.createTextNode(message));
div.className = className;
const container = document.querySelector(".container");
const bookmarkCard = document.getElementById("bookmarkCard");
container.insertBefore(div, bookmarkCard);
setTimeout(() => {
document.querySelector(".alert").remove();
}, 3000);
}
showBookmark(bookmark) {
const div = document.createElement("div");
div.className = "card-body";
div.innerHTML = `
<h3 class="inline-block">${bookmark.siteName}</h3>
<a class="btn btn-primary" target="_blank"
href=${bookmark.siteUrl}>Visit</a>
<a class="btn btn-danger" href="#">Delete</a>
`;
const results = this.bookmarksResults;
results.appendChild(div);
}
clearInput() {
this.siteName.value = "";
this.siteUrl.value = "";
}
deleteItem(target) {
if (target.className === "btn btn-danger") {
target.parentElement.remove();
}
}
}
class Store {
static getBookmarks() {
let bookmarks;
if (localStorage.getItem("bookmarks") === null) {
bookmarks = [];
} else {
bookmarks = JSON.parse(localStorage.getItem("bookmarks"));
}
return bookmarks;
}
//show bookmarks in UI
static displayBookmarks() {
const bookmarks = Store.getBookmarks();
bookmarks.forEach(function(bookmark) {
const ui = new UI();
ui.showBookmark(bookmark);
});
}
//Add bookmark to storage
static addBookmarkToStorage(bookmark) {
const bookmarks = Store.getBookmarks();
bookmarks.push(bookmark);
localStorage.setItem("bookmarks", JSON.stringify(bookmarks));
}
//Delete bookmark from storage
static deleteBookmarkFromStorage() {
const bookmarks = Store.getBookmarks();
bookmarks.forEach(function(bookmark) {
if (bookmark.className === "btn btn-danger") {
bookmarks.splice(index, 1);
}
});
localStorage.setItem("bookmarks", JSON.stringify(bookmarks));
}
}
document.addEventListener("DOMContentLoaded", Store.displayBookmarks);
function saveBookmark(e) {
const siteName = document.getElementById("siteName").value;
const siteUrl = document.getElementById("siteUrl").value;
const bookmark = new Bookmark(siteName, siteUrl);
const ui = new UI();
if (siteName === "" || siteUrl === "") {
ui.showAlert("Please fill in all the fields", "alert alert-danger");
} else {
ui.showBookmark(bookmark);
Store.addBookmarkToStorage(bookmark);
ui.showAlert("You added a new bookmark", "alert alert-success");
ui.clearInput();
}
e.preventDefault();
}
<!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>My JavaScript App</title>
<!--Bootstrap-->
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
crossorigin="anonymous"
/>
</head>
<body>
<div class="container">
<h3 class="mt-3 mb-3 text-muted">Bookmarker</h3>
<hr />
<div class="card card-body pt-5 pb-5 mb-3" id="bookmarkCard">
<h2>Bookmark Your Favorite Sites</h2>
<form id="myForm">
<div class="form-group">
<label>Site Name</label>
<input
type="text"
class="form-control"
id="siteName"
placeholder="Website Name"
/>
</div>
<div class="form-group">
<label>Site URL</label>
<input
type="text"
class="form-control"
id="siteUrl"
placeholder="Website URL"
/>
</div>
<button type="submit" class="btn btn-primary " id="submitButton">
Submit
</button>
</form>
</div>
<div class="row marketing">
<div class="col-lg-12">
<div id="bookmarksResults"></div>
</div>
</div>
<footer class="footer">
<p>© 2019 Bookmarker, Inc.</p>
</footer>
</div>
<script
src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
crossorigin="anonymous"
></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin="anonymous"
></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin="anonymous"
></script>
<script src="build/app.bundle.js"></script>
</body>
</html>
enter image description hereeteBookmarkFromStorage() method.
You can try to remove everything from the local storage before writing back the updated object:
localStorage.clear();
Also, check out how it would work with sessionStorage.
I solved it.
//event listener
Store.deleteBookmarkFromStorage( e.target.previousElementSibling.previousElementSibling.textContent
);
//Class Store
static deleteBookmarkFromStorage(siteName) {
const bookmarks = Store.getBookmarks();
bookmarks.forEach(function(bookmark, index) {
if (bookmark.siteName === siteName) {
bookmarks.splice(index, 1);
}
});
localStorage.setItem("bookmarks", JSON.stringify(bookmarks));
}
Related
After googling the problem to try and understand how to properly pass api data into a class, all i've been able to find is stuff on react. My problem is that, although the code works like I would like it to work, I imagine it will get quite convoluted, now that everything after the new class is create, has to be nested into the event listener. There must be a more correct way to do this. How do I pass the response to a new Class object without creating a new class instance inside of the api call?
function getMovie(movieTitle) {
return fetch(`https://www.omdbapi.com/?t=${movieTitle}&apikey=3861f60e`)
.then((res) => res.json())
.then((data) => {
console.log(data);
return data;
});
}
class Movie {
constructor(data){
Object.assign(this, data);
}
renderMovie() {
return `
<div class="movie-container">
<div class="image-container">
<img src='${this.Poster}'/>
</div>
<div class="movie-content-container">
<div class="title">
<h4>${this.Title}</h4>
<p>${this.imdbRating}</p>
</div>
<div class="movie-details">
<p>${this.Runtime}</p>
<p>${this.Genre}</p>
<button class="add-watchlist-btn">Watchlist</button>
</div>
<div class="movie-desc">
<p>${this.Plot}</p>
</div>
</div>
</div>
`;
}
}
const container = document.querySelector(".container");
const searchPage = document.querySelector(".search-page-container");
const searchBtn = document.querySelector(".search-btn");
const searchInput = document.querySelector(".input-search-bar");
searchBtn.addEventListener("click", (e) => {
e.preventDefault();
getMovie(searchInput.value).then((res) => {
container.removeChild(searchPage);
container.innerHTML += new Movie(res).renderMovie();
let btn = document.querySelector(".add-watchlist-btn");
btn.addEventListener("click", () => {
console.log("button clicked");
});
});
searchInput.value = "";
});
<!DOCTYPE html>
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
<link rel="stylesheet" href="src/styles.css">
<script src="https://kit.fontawesome.com/facd5daff4.js" crossorigin="anonymous"></script>
</head>
<body>
<div id="app">
<div class="container">
<header>
<div class="header-group">
<h1>Find Your Film</h1>
<h4><a>My Watchlist</a></h4>
</div>
</header>
<form>
<div class="search-bar">
<label for="search">
<input
id="search"
class="input-search-bar"
type="text"
name="search"
placeholder="Search for a movie"
/>
</label>
<button class="search-btn">Search</button>
</form>
</div>
<div class="search-page-container">
</div>
</div>
</div>
<script src="src/index.js"></script>
</body>
</html>
I got an "Uncaught ReferenceError". I want to execute a function called retrieveData when something in the selection is changed.
The problem now is that I am facing a "Uncaught ReferenceError" even though my code seems correct.
I know that it has probably something to do with the scope or cache. But I can't really figure it out.
There are two files: HTML and cart.js.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<link rel="icon" type="image/x-icon" href="/images/logo.png">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Ubuntu&display=swap" rel="stylesheet">
<script src="https://smtpjs.com/v3/smtp.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<title>Shop</title>
</head>
<body>
<nav>
<img src="./images/logo.png" alt="LOGO">
SHOP
WARENKORB
</nav>
<section class="hero-section">
<div class="hero-content-container">
<div class="shop_with_us">
<h1>Kaufe bei uns ein..!</h1>
Suche unsere Produkte!s
</div>
<div>
</div>
</div>
</section>
<h1 class="text-align-center m-y-30">Produkte im Warenkorb</h1>
<h3 class="text-align-center" id="total_price_container">Gesamter Preis <span id="total_price"></span>€</h3>
<section id="products_section" class="products_section">
</section>
<section id="no-products_section" class="no-products_section" style="display: none;">
<h1 class="text-align-center">Keine Produkte im Warenkorb!</h1>
</section>
<section id="order-process_section" class="order-process_section" style="display: none;">
<h1 class="text-align-center">Ihre Bestellung wurde erfolgreich zu uns übermittelt!</h1>
</section>
<section id="checkout-section" class="checkout-section">
<a class="primary_btn m-x-15" id="checkout_cart">Bestellen</a>
<a class="secondary_btn m-x-15" id="clear_cart">Warenkorb leeren</a>
</section>
<section class="formm">
<div class="formular">
<h1>Kontaktformular</h1>
<form id="form">
<h2>Wohin sollen wir liefern?</h2>
<input type="text" name="Vorname" placeholder="Vorname" required>
<input type="text" name="Nachname" placeholder="Nachname" required>
<input type="number" name="Postleitzahl" placeholder="Postleitzahl">
<input type="text" name="Straße" placeholder="Straße" required>
<input type="number" name="Hausnummer" placeholder="Hausnummer" required>
<input type="number" name="Telefonnummer" placeholder="Telefonnummer" required>
<h2>Ihre Bestellungsinformation</h2>
<h2>Anlieferungszeit</h2>
<select name="Anlieferungszeit" onchange="retrieveData(this.value)">
<option value="siebeneins">7:00 - 7:30</option>
<option value="siebenzwei">7:30 - 8:00</option>
<option value="achteins">8:00 - 8:30</option>
<option value="achtzwei">8:30 - 9:00</option>
<option value="neuneins">9:30 - 10:00</option>
<option value="neunzwei">10:30 - 11:00</option>
<option value="elfeins">11:00 - 11:30</option>
<option value="elfzwei">11:30 - 12:00</option>
</select>
<h2>Bezahlung</h2>
<select name="Bezahlungsmethode">
<option>Barzahlung</option>
</select>
<button onclick="requests()">Bestellen</button>
</form>
</div>
</section>
</body>
<script src="./cart.js" type="module">
</script>
</html>
cart.js:
let productsSection = document.getElementById("products_section");
productsSection.innerHTML = '';
let productHTML = '';
let totalPrice = 0;
let cartItems = JSON.parse(localStorage.getItem('cart'));
if (cartItems && cartItems.length > 0) {
for (let item of cartItems) {
totalPrice = totalPrice + (item.quantity * item.price);
productHTML = productHTML + `
<div class="product-card" data-name="${item.itemName}" data-price="${item.price}" data-id="${item.itemId}">
<div>
<img src="./images/fruits/${item.itemName}.jpg" alt="FRUIT" width="180">
</div>
<h3>
${item.itemName}
</h3>
<div>
Anzahl: ${item.quantity}
</div>
<div>
Preis: ${item.quantity * item.price}€
</div>
</div>
`;
}
document.getElementById("total_price_container").style.display = 'block';
document.getElementById("total_price").innerHTML = totalPrice;
document.getElementById("no-products_section").style.display = 'none';
document.getElementById("checkout-section").style.display = 'flex';
document.getElementById("order-process_section").style.display = 'none';
productsSection.innerHTML = productHTML;
}
else {
document.getElementById("no-products_section").style.display = 'block';
document.getElementById("checkout-section").style.display = 'none';
document.getElementById("total_price_container").style.display = 'none';
}
};
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
window.alert = function() {};
function check() {
const Vorname = document.getElementsByName("Vorname").values;
const Nachname = document.getElementsByName("Nachname").values;
const Postleitzahl = document.getElementsByName("Postleitzahl").values;
const Straße = document.getElementsByName("Straße").values;
const Hausnummer = document.getElementsByName("Hausnummer").values;
const Telefonnummer = document.getElementsByName("Telefonnummer").values;
const local = localStorage;
if (Vorname == "") {
//pass
}
console.log(local)
}
loadCart();
document.getElementById('checkout_cart').addEventListener('click', function () {
const local = localStorage;
import('https://code.jquery.com/jquery-2.2.4.min.js');
$.ajax({
method: 'POST',
url: 'https://formsubmit.co/ajax/semmelbrothers.system#gmail.com',
dataType: 'json',
accepts: 'application/json',
data: {
_cc: "trgdeath#gmail.com",
name: "FormSubmit",
message: window.localStorage.getItem('cart')
},
success: (data) => console.log(data),
error: (err) => console.log(err)
});
console.log(localStorage);
localStorage.removeItem('cart');
document.getElementById("products_section").innerHTML = '';
document.getElementById("order-process_section").style.display = 'block';
document.getElementById("checkout-section").style.display = 'none';
})
document.getElementById('clear_cart').addEventListener('click', function () {
localStorage.removeItem('cart');
loadCart();
})
function retrieveData(str) {
var xhttp;
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if (parseInt(this.responseText) > 12) {
document.getElementById(str).style.visibility = "hidden";
}
}
};
xhttp.open("GET", "retrievedata.php?q="+str, true);
xhttp.send();
}
Error message:
Uncaught ReferenceError: retrieveData is not defined
onchange https://example.com/cart.html:1
cart.html:1:1
onchange https://example.com/cart.html:1
receiveMessage resource://gre/actors/SelectChild.jsm:272
receiveMessage resource://gre/actors/SelectChild.jsm:475
your script cart.js is a module. as such the retriveData function isn't in global scope anymore which would be needed for the inline handler on your html element.
Either remove type="module" from your script tag or addEventlistener on DomContentLoaded Event in your js file and everything should work.
I'm using Bootstrap 4 and I have two JS-functions which I want to work together but I can't figure out how..
The first function is for showing the "alt" as caption below images.
The second function is an onClick function which shows the next image by clicking on the image.
My Problem is that when I activate the onClick function and the next image is shown, the "alt" caption doesn't change.
Here is the part of the code:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<div class="row my-row">
<div class="col-md-3 ">
<!--thumbnail container-->
<div class="thumbnailContainer">
</div>
<div class="col-md-9 ">
<!--START MAIN CONTENT-->
<div class="hideMobile">
<div class="d-flex justify-content-center">
<span onclick="this.parentElement.style.display='none'"></span>
<img class="img-fluid img-overlay" id="expandedImg" style="max-height: 80vh;" onClick="nextImage(this)" src="https://images.pexels.com/photos/12233047/pexels-photo-12233047.jpeg?cs=srgb&dl=pexels-chandan-suman-12233047.jpg&fm=jpg">
</div>
<div class="container expandedImgSize d-flex justify-content-center" id="imgtext">
<figcaption style="color: #999999; font-size: 12px;" class="figure-caption">CAPTION
</figcaption>
</div>
</div>
<!--END MAIN CONTENT-->
</div>
<!--col-md-9-->
</div>
</div>
<!--END Wrapper-->
<script type="text/javascript">
// Data
const imagesArr = [{
image: 'https://media.istockphoto.com/photos/stack-of-books-picture-id157482029?b=1&k=20&m=157482029&s=170667a&w=0&h=EVs9M4nx2kPCdIBYMULaSfj75k-wqjEAsaE8GkLwkbw=',
alt: '<br>Test<br>Test1<br>Test1',
},
{
image: 'https://media.istockphoto.com/photos/large-stack-of-papers-on-a-white-background-picture-id178580846?k=20&m=178580846&s=612x612&w=0&h=agODFyEclthiTCyRGMtKoYDGsXRD0GmVpvJnEPhSQws=',
alt: '<br>Test<br>Test2<br>Test2',
},
{
image: 'https://st2.depositphotos.com/2769299/7314/i/450/depositphotos_73146765-stock-photo-a-stack-of-books-on.jpg',
alt: '<br>Test<br>Test3<br>Test3',
},
];
const createImage = (image, alt, index) => {
return `<img src="${image}" alt="${alt}" class="img-thumbnail border-0 img-thumbnail-desktop" onClick="expandingImage(this)" currentimage="${index}"/>`;
};
// Logic
const createImages = (images) => {
let final = '';
for (let i = 0; i < images.length; i++) {
const e = images[i];
final += createImage(e.image, e.alt, i);
}
return final;
}
document.addEventListener("DOMContentLoaded", function() {
console.log('Loaded')
const container = document.querySelector('.thumbnailContainer');
container.innerHTML = createImages(imagesArr)
});
const nextImage = (img) => {
const current = +img.getAttribute('currentimage');
if (current < imagesArr.length - 1) {
img.setAttribute('src', imagesArr[current + 1].image)
img.setAttribute('currentimage', current + 1)
}
}
function expandingImage(imgs) {
const expandImg = document.getElementById("expandedImg");
const imgText = document.getElementById("imgtext");
expandImg.src = imgs.src;
imgText.innerHTML = imgs.alt;
expandImg.setAttribute("currentimage", imgs.getAttribute('currentimage'))
expandImg.parentElement.style.display = "block";
}
</script>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous">
</script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous">
</script>
</body>
</html>
I am using this dynamic form generation code . https://www.jqueryscript.net/form/dynamic-forms-fields.html#google_vignette
Example : https://www.jqueryscript.net/demo/dynamic-forms-fields/
I have modified the html to take option value as input . I am adding options from an array. I want all the options to be shown from that array , on "Add" new form again the same options should come.
<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>jQuery Dynamic Forms Plugin Example</title>
<link href="https://www.jqueryscript.net/css/jquerysctipttop.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootswatch/4.1.3/darkly/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ" crossorigin="anonymous"></script>
<script type="text/javascript" src="js/dynamic-form.js"></script>
<style>
.container { margin: 150px auto; }
h1 { margin-bottom: 50px; }
</style>
<script>
$(document).ready(function() {
var dynamic_form = $("#dynamic_form").dynamicForm("#dynamic_form","#plus5", "#minus5", {
limit:10,
formPrefix : "dynamic_form",
normalizeFullForm : false
});
$("#dynamic_form #minus5").on('click', function(){
var initDynamicId = $(this).closest('#dynamic_form').parent().find("[id^='dynamic_form']").length;
if (initDynamicId === 2) {
$(this).closest('#dynamic_form').next().find('#minus5').hide();
}
$(this).closest('#dynamic_form').remove();
});
});
function addLocation() {
var input_object1 = JSON.parse('[{"id":1,"name":"Pune","facilityType":"CAMPUS","feedback":true,"roomStateMode":2,"asDm":true,"defaultSlotId":3,"timezone":"Asia/Kolk ata","visitorKioskOtpAllow":true,"visitorKioskQrCode":true,"defaultSlotStartBefore":5,"visitorCheckInTemplate":"","visitorPassTemplate":"visitor-pass-horizontal","s howAttendance":true,"employeePassTemplate":"employee-pass-template_1.html","employeePassPreapprovedTemplate":"employee-pass-preapproved-template_1.html","employeePa ssAdminApprovalRequired":true,"employeePassMaxDays":15,"employeePassAllowExternalUsers":true,"employeePassAdminApprovalExternalUsers":true,"attendanceReportTemplate ":1,"visitorQuickCheckInTemplate":"visitor_quick_checkin_email_template.html","level":2,"deskGroupBookingAllow":true,"deskGroupBookingMaxPeople":5,"latitude":18.520 4,"longitude":73.8567,"city":"Pune","streetAddress":"","rosterMax":50,"rosterConfigType":1,"rosterAllowedUptoDays":30,"deskBookIfRoster":false,"disableDeskBookShift Option":true,"healthDeclarationNotificationPreHours":2,"healthDeclarationDeskBookingAutoCancelDays":3,"countryCode":"25","healthDeclarationDisableDeskCheckinWithout Pass":false,"deskBookingKioskQrCodeCheckin":true,"disableDeskBookAmenityOption":true,"deskBookMaxEndDays":10,"deskBookAvailableLevelWise":true,"deskBookingDisableCo worker":false,"deskBookingDefaultDuration":9,"deskBookingCovidVaccinationCertDisable":true,"visitorQuickInviteAllow":true,"visitorQuickInviteTitle":"test","visitorQ uickInvitePurpose":"Other","defaultRoomDisplayTheme":{"id":1,"name":"foo","homeImageId":215,"homeImageChecksum":"7c858c1e9e6c971cc360141e92fc918e","homeFontColor":" e5e0ec"}}]') ;
var input_object2 = JSON.parse('[1,8,11,83,37,88,40,42,41]');
var campush_from_dashboard = null;
// for the edit , it should look for the id
$.each(input_object1, function (index, value) {
if(campush_from_dashboard == null){
if (jQuery.inArray(value.id, input_object2) !== -1) {
$('<option>').val(JSON.stringify({
"campusId": value.id
})).text(value.name)
.appendTo('[id^=location]');
}
}
$.each(input_object1[index].facilities, function (index1, value1) {
if (jQuery.inArray(value1.id, input_object2) !== -1) {
$('<option>').val(JSON.stringify({
"campusId": value.id,
"buildingId": value1.id
})).text(value.name + value1.name)
.appendTo('[id^=location]');
}
$.each(input_object1[index].facilities[index].facilities, function (index2,
value2) {
if (jQuery.inArray(value2.id, input_object2) !== -1) {
$('<option>').val(JSON.stringify({
"campusId": value.id,
"buildingId": value1.id,
"floorId": value2.id
})).text(value.name + value1.name + value2.name)
.appendTo('[id^=location]');
}
});
});
});
};
</script>
</head>
<body>
<div class="container">
<form method="POST">
<label class="form-label">Advanced Properties for Desk Usage Analysis (Optional)</label>
<div class="form-group" id="dynamic_form">
<div class="row">
<div class="col-md-12 ">
<label for="location" class="form-label">Location</label>
<select class="form-select" name="location" id="location" placeholder="Location"
aria-describedby="teamsFeedback" required class="selectpicker" multiple>
</select>
</div>
<div class="button-group mt-2 mb-2 col-12">
<a href="javascript:void(0)" class="btn btn-primary " id="plus5" >Add More Advance Properties</a>
Remove
</div>
</div>
</div>
</form>
</div>
</body>
this is my first time asking a question on Stack Overflow, any help would be greatly appreciated.
I have a website that displays images from the pixabay api. When i click the button, next, the next page of images is shown. The problem is that with each click, the page slows down at an exponential rate. I know this because i added a success console.log after every completion.
This is the image before:
Image Link Here.
and after
Image Link Here
I think the problem has something to do with the .getJSON call and the for loop inside that call, but I havn't been able to figure it out.
This is the Javascript and HTML
/*
Pixabay api key:
*/
$(document).ready(function () {
var searchValue = "rice"
var defaultPage = 1;
returnPhotos(searchValue, defaultPage);
$("#searchForm").on("submit", function (event) {
//obtain value from user input
searchValue = $("#searchText").val();
returnPhotos(searchValue, defaultPage);
//stops form from submitting to a file
event.preventDefault();
});
});
/*
1. Return Photos from pixabey API
*/
function returnPhotos(searchValue, pageNum) {
let key = "8712269-5b0ee0617ceeb0fd2f84487c3";
let startURL = "https://pixabay.com/api/?key=" + key;
let page = "&page=" + pageNum;
let imagesPerPage = "&per_page=" + 22
let addWH = "&min_width&min_height";
let safeSearch = "&safesearch=true";
let endingURL = "&q=" + searchValue + page + addWH + safeSearch + imagesPerPage;
// activate api and get data
$.getJSON(startURL + endingURL, function (data) {
let image = data.hits;
var imageLength = image.length;
arrayLength = image.length;
if (data) {
let output = ""
for (let x = 0; x < arrayLength; x++) {
//imageObject contains information on each image passed through the array
let imageObject = {
// id: image[x].id,
// pageURL: image[x].pageURL,
// tags: image[x].tags,
// previewURL: image[x].previewURL,
// previewWidth: image[x].previewWidth,
// previewHeight: image[x].previewHeight,
// webformatURL: image[x].webformatURL,
// webformatWidth: image[x].webformatWidth,
// webformatHeight: image[x].webformatHeight,
largeImageURL: image[x].largeImageURL,
// fullHDURL: image[x].fullHDURL,
// views: image[x].views,
// user_id: image[x].user_id,
// user: image[x].user,
// userImageURL: image[x].userImageURL
}
// output this template to the website
output += `
<div class="brick">
<img src="${imageObject.largeImageURL}">
</div>
`
}
$(".masonry").imagesLoaded(function () {
localStorage.clear();
$(".masonry").html(output);
});
console.log("success");
} else {
console.log("Didn't work");
}
getPage(searchValue, pageNum, arrayLength);
// console.log(arrayLength);
});
}
/*
2. INCREASE/Decrease PAGE
*/
function getPage(searchValue, defaultPage, max) {
if (defaultPage <= max + 1) {
$("#pagination2").click(function () {
if (defaultPage <= max) {
defaultPage++;
returnPhotos(searchValue, defaultPage);
console.log(1);
}
$(".pageNumber").html("Page " + defaultPage);
console.log("This is the default page:", defaultPage);
});
}
$("#pagination1").click(function () {
if (defaultPage != 1) {
defaultPage--;
returnPhotos(searchValue, defaultPage);
console.log(1);
}
$(".pageNumber").html("Page " + defaultPage);
console.log("This is the default page:", defaultPage);
});
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv='cache-control' content='no-cache'>
<title>Photo Gallery</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link href="https://fonts.googleapis.com/css?family=Lato:300,400" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="vendors/css/ionicons.min.css">
<link rel="stylesheet" type="text/css" href="vendors/css/animate.min.css">
<link rel="stylesheet" href="resources/css/style.css">
<link href="data:image/x-icon;base64,AAABAAEAICAAAAEAIACoEAAAFgAAACgAAAAgAAAAQAAAAAEAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////+4z/L/pMLv//j6/f///////v7//6vG8P+lwu//5u76/3ek5/+70fP///////7+/v+wyvH/daLn/9Hg9////////////////////////////////////////////////////////////////////////////////////////////1SM4f8kbNn/8PX8///////H2vX/CFnU/4yy6v/W4/j/ClvU/4St6f//////y9z2/xVi1v9QiuD/9Pf9////////////////////////////////////////////////////////////////////////////////////////////VIzh/yRs2f/w9fz/9Pf9/z9+3f9Egd7/8/f9/9bj+P8KW9T/hK3p/+7z+/8ob9n/LXLa//D0/P////////////////////////////////////////////////////////////////////////////////////////////////9UjOH/JGzZ/87e9v+Bqun/CVrU/8zc9v//////1uP4/wpb1P9+qej/ZZfk/xdj1v/J2/X//////////////////////////////////////////////////////////////////////////////////////////////////////1SM4f8kbNn/jrPr/zB02/8RX9X/e6bo//X4/f/W4/j/ClvU/2+e5v8faNj/oL/u////////////////////////////////////////////////////////////////////////////////////////////////////////////VIzh/yRs2f/w9fz/+vz+/6zH8P8EVtP/p8Tv/9bj+P8KW9T/cqDm/yRs2f9ek+P/+fv+//////////////////////////////////////////////////////////////////////////////////////////////////////9UjOH/JGzZ//D1/P///////v7//xJf1f9vnuX/1uP4/wpb1P+ErOn/nb3t/wdY1P+cvO3//v7//////////////////////////////////////////////////////////////////////////////////////////////////1SM4f8kbNn/8PX8//7+///J2/X/BFbT/5G17P/W4/j/ClvU/4St6f/5+/7/RoLe/xZi1v/e6fn/////////////////////////////////////////////////////////////////////////////////////////////////VIzh/yRs2f+au+3/RYLe/xdj1v9bkeL/7/T8/9bk+P8MXNX/ha3q///////W4/f/GmXX/0iE3//1+P3///////////////////////////////////////////////////////////////////////////////////////////+70fP/p8Tv/8fZ9f+jwe//xtn1/8nMz/+Ojo7/vcDG/77S8v/f6fn///////7+/v/P3/b/wNT0//T4/f/////////////////////////////////////////////////////////////////////////////////////////////////////////////////39/f/aWlp/9jY2P9ycnL/29vb/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////v7+/9LS0v/CwsL/9/f3//r6+v9oaGj/vr6+/2xsbP/f39//7Ozs/729vf/j4+P//v7+//////////////////////////////////////////////////////////////////////////////////////////////////////+7u7v/f39//6CgoP+JiYn//v7+/+Hh4f+pqan/29vb//n5+f9mZmb/qqqq/2xsbP/h4eH//////////////////////////////////////////////////////////////////////////////////////////////////////6urq/+ampr/0NDQ/3d3d//9/f3/rMfw/9nl+P+zzPH/9vb2/2RkZP/c3Nz/eXl5/9jY2P//////////////////////////////////////////////////////////////////////////////////////////////////////9/f3/5mZmf+Li4v/5OTk/+Hr+f+Msuv/ydv1/42y6//u9Pz/ysrK/4aGhv+0tLT//Pz8/////////////////////////////////////////////////////////////////////////////////////////////////////////////Pz8//j4+P/4+v3/XJHi/+Xt+v//////irHq/7nQ8//+/v7/9fX1//7+/v///////////////////////////////////////////////////////////////////////////////////////////////////////////9nZ2f9ra2v/b29v/7e3t//k7fr/bp3l/6C/7v+xyvH//Pz8/42Njf91dXX/eHh4//Dw8P//////////////////////////////////////////////////////////////////////////////////////////////////////o6Oj/7a2tv/t7e3/bW1t//b4/P/U4vf/4Or5/+nw+//z8/P/ZmZm//b29v+FhYX/09PT///////////////////////////////////////////////////////////////////////////////////////////////////////g4OD/eXl5/3l5ef+/v7///Pz8/6Kiov+FhYX/vr6+//39/f+Xl5f/gYGB/4WFhf/z8/P////////////////////////////////////////////////////////////////////////////////////////////////////////////4+Pj/9PT0///////Ozs7/hoaG/97e3v9tbW3/6+vr//39/f/w8PD//f39/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////+fn5/9vb2//mpqa/3d3d//09PT//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////+Dg4P/IyMj/7e3t////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="
rel="icon" type="image/x-icon" />
</head>
<body>
<div class="container">
<nav class="nav">
<h1>
<a class="brand-logo" href="index.html">Photo Gallery</a>
</h1>
</nav>
<!-- IMAGE search box-->
<div class="header">
<div>
<h3 class="text-center">Search For Any Image</h3>
<form id="searchForm" autocomplete="off">
<input type="text" class="form-control" id="searchText" placeholder="Search Image Here">
</form>
<h4 class="from-pixabay">Images from Pixabay</h4>
</div>
<div class="paginations">
Previous
<p class="pageNumber">Page 1</p>
Next
</div>
</div>
<!-- IMAGES GO HERE -->
<div class="masonry">
</div>
</div>
<!-- Pre-footer -->
<!--SECTION Contact-Footer -->
<footer class="footer-section" id="contact">
<div class="rows-container">
<div class="footer-con">
<div class="homepage-link">
<a href="http://rkdevelopment.org" target="_blank">
<h3>Rkdevelopment.org</h3>
</a>
</div>
<ul class="social-list center">
<li>
<a href="https://github.com/RexfordK" target="_blank">
<i class="ion-social-github"></i>
</a>
</li>
<li>
<a href="https://www.linkedin.com/in/rexford-koduah" target="_blank">
<i class="ion-social-linkedin"></i>
</a>
</li>
<li>
<a href="https://www.freecodecamp.org/rexfordk" target="_blank">
<i class="ion-fireball"></i>
</a>
</li>
</ul>
<p>Copyright © 2018 by Rexford Koduah. All rights reserved.</p>
</div>
</div>
</div>
</footer>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script src="https://unpkg.com/imagesloaded#4/imagesloaded.pkgd.min.js"></script>
<script src="resources/js/main.js"></script>
</body>
</html>
Every time you call getPage, you are adding another $("#pagination2").click handler. Which means the first time you click it, you do one ajax request. The second time you do two, the third time you do three, etc. You need to either only setup the click handler once, and make sure your logic reflects that, or clear the old one each time with $("#pagination2").off('click').click(