Been working on hangman using javascript and HTML, problem is whenever i click on a letter it doesn't replace the "_"
var myList=["Computer","Algorithm","Software","Programming","Developer"];
var n;
var star=" _";
console.log(myList)
computer=myList[Math.floor(Math.random() * myList.length)];
console.log(computer);
var word= document.getElementById("word").innerHTML=star.repeat(computer.length);
var letter=document.getElementsByClassName("col")
function myFunction(){
n=word.replace(star,letter);
};
for (var i=0; i<letter.length;i++){
letter[i].addEventListener("click",myFunction());
}
myFunction();
letter is basically alphabet(they are not buttons they are divs)
word is also an empty div in which the "-" goes in
in conclusion i want to replace word("-") with letters(which ever letter you click on)
Here is the working example:
var myList=["Computer","Algorithm","Software","Programming","Developer"];
var star="_";
var wrapper = document.querySelector('.wrapper');
for(var i = 0; i<myList.length; i++) {
var list = document.createElement('div');
list.setAttribute('class', 'wrapper-list');
list.setAttribute('id', 'list'+i);
wrapper.appendChild(list);
for(var j=0; j<myList[i].length;j++) {
var item = document.createElement('div');
item.setAttribute('class', 'wrapper-list__item');
item.innerText = myList[i][j];
list.appendChild(item);
item.onclick = function(e) {
this.innerText = star;
}
}
}
.wrapper .wrapper-list {
display: flex;
}
.wrapper .wrapper-list__item {
padding: 5px 10px;
border: 1px solid #dedede;
margin: 5px;
text-transform: uppercase;
cursor: pointer;
}
<div class="wrapper"></div>
Related
i am trying to create Vanilla Javascript Pagination and i have a problem because it looks like my pagination is only working when there is 7 pages,when that number switches there are small bugs but i cant find a way to optimise better my code and to make the code be usable for any number of page.Here is the code:
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" />
<title>Document</title>
<link
href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65"
crossorigin="anonymous" />
<link rel="stylesheet" href="./main.css" />
</head>
<body>
<section class="blog-listing">
<div class="container">
<div class="row">
<div class="col-6">
<input
type="search"
class="inputs"
id="searcher"
placeholder="Search" />
<input type="hidden" name="type" value="BLOG_POST" />
<input type="hidden" name="type" value="LISTING_PAGE" />
</div>
<div class="col-6"></div>
</div>
<div class="row" id="blogs"></div>
<div id="blog-pagination"></div>
<div id="buttons"></div>
</div>
</section>
<script
src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/js/bootstrap.bundle.min.js"
integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4"
crossorigin="anonymous"></script>
<script src="./main.js"></script>
</body>
</html>
CSS
.blog-listing {
padding: 200px 0px;
}
.blog-listing input {
background-color: #f3f3f3;
border-radius: 40.5px;
width: 100%;
padding: 20px;
margin-bottom: 20px;
}
.blog-listing input::-moz-placeholder {
font-family: "Poppins";
font-weight: 300;
font-size: 18px;
line-height: 44px;
color: #19212f;
}
.blog-listing input:-ms-input-placeholder {
font-family: "Poppins";
font-weight: 300;
font-size: 18px;
line-height: 44px;
color: #19212f;
}
.blog-listing input::placeholder {
font-family: "Poppins";
font-weight: 300;
font-size: 18px;
line-height: 44px;
color: #19212f;
}
.blog-listing__card {
background: #ffffff;
box-shadow: 0px 0px 40px rgba(0, 0, 0, 0.105633);
border-radius: 4px;
padding-bottom: 100px;
margin-top: 50px;
}
.blog-listing__card__image img {
width: 100%;
}
.blog-listing__card__text {
padding: 30px 40px 60px;
}
.blog-listing__card__text a {
font-family: "Poppins";
font-weight: 700;
font-size: 16px;
line-height: 25px;
color: #089fd9;
}
.blog-listing__card__text p {
font-family: "Poppins";
font-weight: 700;
font-size: 16px;
line-height: 25px;
color: #878787;
padding-top: 15px;
}
.blog-listing__card__text h1,
.blog-listing__card__text h2,
.blog-listing__card__text h3 {
font-family: "Poppins";
font-weight: 700;
font-size: 22px;
line-height: 53px;
letter-spacing: -0.392857px;
color: #293241;
}
.blog-listing__card__divider {
border: 1px solid #cccccc;
}
.blog-listing__card.is-hidden {
opacity: 0;
}
.blog-listing__card__topics ul {
list-style-type: none;
}
.blog-listing__card__topics ul li a {
font-family: "Abel";
font-weight: 400;
font-size: 12px;
line-height: 25px;
color: #293241;
opacity: 0.5;
}
.blog-tag-filter {
background-color: transparent;
border: 0;
border-radius: 0;
padding: 0;
}
#media (max-width: 767px) {
.blog-tag-filter {
margin-bottom: 1.5rem;
text-align: center;
}
}
.blog-tag-filter__title {
color: #fff;
margin-right: 1.5rem;
}
.blog-tag-filter__select-wrapper {
display: inline-block;
max-width: 100%;
position: relative;
width: 100%;
}
.blog-tag-filter__select {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
display: inline-block;
padding: 1.25rem 4.5rem 1.25rem 2.75rem;
background-color: #f3f3f3;
border-radius: 40.5px;
padding: 18px;
width: 100%;
max-width: 100%;
font-family: "Poppins";
font-weight: 300;
font-size: 18px;
color: #19212f;
}
.blog-tag-filter__select-wrapper:after {
color: #19212f;
content: "▾";
pointer-events: none;
position: absolute;
right: 0.7rem;
top: 50%;
transform: translateY(-50%);
}
#blog-pagination {
text-align: center;
padding: 50px 0px;
}
#buttons input {
display: inline-block;
cursor: pointer;
border: 0.75px solid #bbbbbb;
border-radius: 4px;
padding: 20px;
width: 100px;
text-align: center;
background-color: white;
color: #089fd9;
}
#buttons {
text-align: center;
}
.active {
background-color: #089fd9 !important;
color: #ffffff !important;
}
:disabled {
cursor: not-allowed !important;
color: gray !important;
background-color: #f1f1f1 !important;
}
.none {
display: none !important;
}
JS
let allBlogs = [];
allBlogs.length = 14;
let blog_div = document.getElementById("blogs");
let blogTagSelect = document.querySelector("#tag-select");
// let selectedItem = blogTagSelect.options[blogTagSelect.selectedIndex];
let countList = new Array();
let addPageList = new Array();
let presentPage = 1;
let countPerEachPage = 2;
let countOfPages = 0;
let buttons = document.getElementById("buttons");
function prepareList() {
let inputFirst = document.createElement("input");
inputFirst.setAttribute("type", "button");
inputFirst.setAttribute("id", "first");
inputFirst.setAttribute("value", "first");
inputFirst.onclick = function () {
presentPage = 1;
loadMyPaginationList();
for (let i = 0; i < pageBtns.length; i++) {
pageBtns[i].classList.remove("active");
if (Number(pageBtns[i].value) == presentPage) {
pageBtns[i].classList.add("active");
}
if (pageBtns[i].classList.contains("active")) {
pageBtns[i].classList.remove("none");
for (let j = 0; j < pageBtns.length; j++) {
if (pageBtns[j].value > 2) {
pageBtns[j].classList.add("none");
pageBtns[1].classList.remove("none");
if (pageBtns[j].value > pageBtns.length - 2) {
pageBtns[j].classList.remove("none");
}
}
}
}
}
};
let inputPrevious = document.createElement("input");
inputPrevious.setAttribute("type", "button");
inputPrevious.setAttribute("id", "previous");
inputPrevious.setAttribute("value", "previous");
inputPrevious.onclick = function () {
presentPage -= 1;
loadMyPaginationList();
for (let i = 0; i < pageBtns.length; i++) {
pageBtns[i].classList.remove("active");
if (Number(pageBtns[i].value) == presentPage) {
pageBtns[i].classList.add("active");
pageBtns[i].classList.remove("none");
if (Number(pageBtns[i].value) < Math.ceil(pageBtns.length / 2)) {
pageBtns[i + 2].classList.add("none");
}
if (Number(pageBtns[i].value) == pageBtns.length - 2) {
pageBtns[i - 1].classList.remove("none");
for (let j = 0; j < pageBtns.length; j++) {
if (pageBtns[j].value < Math.ceil(pageBtns.length / 2)) {
pageBtns[j].classList.add("none");
}
}
}
}
}
};
buttons.appendChild(inputFirst);
buttons.appendChild(inputPrevious);
for (count = 0; count < allBlogs.length; count++) {
countList.push(count);
}
countOfPages = getCountOfPages();
for (let i = 1; i <= countOfPages; i++) {
let inputButton = document.createElement("input");
inputButton.setAttribute("type", "button");
inputButton.setAttribute("class", "page-buttons");
inputButton.setAttribute("value", i);
inputButton.onclick = function () {
presentPage = Number(inputButton.value);
loadMyPaginationList();
};
buttons.appendChild(inputButton);
if (
inputButton.value > presentPage + 1 &&
inputButton.value < countOfPages - 1
) {
inputButton.classList.add("none");
if (Number(inputButton.value) == countOfPages - 2) {
let Dots = document.createElement("input");
Dots.setAttribute("value", "...");
Dots.setAttribute("class", "dots");
buttons.appendChild(Dots);
}
}
}
let inputNext = document.createElement("input");
inputNext.setAttribute("type", "button");
inputNext.setAttribute("id", "next");
inputNext.setAttribute("value", "next");
inputNext.onclick = function () {
presentPage += 1;
loadMyPaginationList();
for (let i = 0; i < pageBtns.length; i++) {
pageBtns[i].classList.remove("active");
if (Number(pageBtns[i].value) == presentPage) {
pageBtns[i].classList.add("active");
if (pageBtns[i + 1] != null) {
pageBtns[i + 1].classList.remove("none");
pageBtns[i - 1].classList.add("none");
}
if (Number(pageBtns[i].value - 1) >= Math.ceil(pageBtns.length / 2)) {
pageBtns[i - 1].classList.remove("none");
} else {
pageBtns[i - 1].classList.add("none");
}
if (pageBtns[i].classList.contains("active")) {
pageBtns[i].classList.remove("none");
if (pageBtns[i - 2] != null) {
pageBtns[i - 2].classList.add("none");
if (pageBtns[i].value > Math.ceil(pageBtns.length / 2 + 1)) {
pageBtns[i - 2].classList.remove("none");
}
}
}
}
}
};
let inputLast = document.createElement("input");
inputLast.setAttribute("type", "button");
inputLast.setAttribute("id", "last");
inputLast.setAttribute("value", "last");
inputLast.onclick = function () {
presentPage = countOfPages;
loadMyPaginationList();
for (let i = 0; i < pageBtns.length; i++) {
pageBtns[i].classList.remove("active");
if (Number(pageBtns[i].value) == presentPage) {
pageBtns[i].classList.add("active");
}
}
};
buttons.appendChild(inputNext);
buttons.appendChild(inputLast);
let pageBtns = document.querySelectorAll(".page-buttons");
for (let i = 0; i < pageBtns.length; i++) {
if (Number(pageBtns[i].value) == presentPage) {
pageBtns[i].classList.add("active");
}
pageBtns[i].addEventListener("click", function () {
let current = document.getElementsByClassName("active");
if (current.length > 0) {
current[0].classList.remove("active");
}
pageBtns[i].classList.add("active");
});
}
}
//function for creating how many how many number per each page
function getCountOfPages() {
return Math.ceil(countList.length / countPerEachPage);
}
//function for creating how to move between the pages
function loadMyPaginationList() {
let offset = (presentPage - 1) * countPerEachPage + 1 - 1;
let start = (presentPage - 1) * countPerEachPage;
let end = start + countPerEachPage;
addPageList = countList.slice(start, end);
createPageList();
validatePageCount();
}
//function for adding numbers to each page
function createPageList() {
blog_div.innerHTML = "";
let indexEnd =
presentPage * countPerEachPage <= allBlogs.length
? presentPage * countPerEachPage
: allBlogs.length;
for (let i = (presentPage - 1) * countPerEachPage; i < indexEnd; i++) {
let bootstrapDiv = document.createElement("div");
bootstrapDiv.classList = "col-lg-4 col-md-6 col-sm-12";
let card = document.createElement("div");
card.classList = "blog-listing__card";
let cardImage = document.createElement("div");
cardImage.classList = "blog-listing__card__image";
let link = document.createElement("a");
link.setAttribute("href", "#");
let img = document.createElement("img");
img.setAttribute("src", "./Bitmap.svg");
let cardText = document.createElement("div");
cardText.classList = "blog-listing__card__text";
let cardTitle = document.createElement("h2");
cardTitle.innerText = `Naslov ${i}`;
let textLink = document.createElement("a");
textLink.setAttribute("href", "#");
textLink.innerText = `Datum | Autor`;
let textText = document.createElement("p");
textText.innerText = `Opis`;
let topics = document.createElement("div");
topics.classList = "blog-listing__card__topics";
let topicList = document.createElement("ul");
let topicLi = document.createElement("li");
let topicLink = document.createElement("a");
topicLink.setAttribute("href", "#");
topicLink.innerText = `Tagovi`;
let divider = document.createElement("div");
divider.classList = "blog-listing__card__divider";
cardText.appendChild(cardTitle);
cardText.appendChild(textLink);
cardText.appendChild(textText);
link.appendChild(img);
cardImage.appendChild(link);
topicLi.appendChild(topicLink);
topicList.appendChild(topicLi);
topics.appendChild(topicList);
card.appendChild(cardImage);
card.appendChild(cardText);
card.appendChild(topics);
card.appendChild(divider);
bootstrapDiv.appendChild(card);
blog_div.appendChild(bootstrapDiv);
}
}
//function for validating real time condition like if move to last page, last page disabled etc
function validatePageCount() {
let inputFirst = document.getElementById("first");
let inputPrevious = document.getElementById("previous");
let inputNext = document.getElementById("next");
let inputLast = document.getElementById("last");
let PBtn = document.querySelectorAll(".page-buttons");
if (presentPage == 1) {
inputFirst.setAttribute("disabled", "");
inputPrevious.setAttribute("disabled", "");
} else {
inputFirst.removeAttribute("disabled");
inputPrevious.removeAttribute("disabled");
}
if (presentPage == countOfPages) {
inputNext.setAttribute("disabled", "");
inputLast.setAttribute("disabled", "");
} else {
inputNext.removeAttribute("disabled");
inputLast.removeAttribute("disabled");
}
}
//function for loading pagination functionality
function loadMyPagination() {
prepareList();
loadMyPaginationList();
}
window.onload = loadMyPagination;
function liveSearch() {
let searchQuery = document.getElementById("searcher").value;
let cards = document.querySelectorAll(".blog-listing__card");
for (let i = 0; i < cards.length; i++) {
if (cards[i].querySelector("h1, h2, h3").outerText !== null) {
if (
cards[i]
.querySelector("h1, h2, h3")
.outerText.toLowerCase()
.includes(searchQuery.toLowerCase())
) {
cards[i].classList.remove("is-hidden");
} else {
cards[i].classList.add("is-hidden");
}
}
}
}
let typingTimer;
let typeInterval = 300;
let searchInput = document.getElementById("searcher");
searchInput.addEventListener("keyup", () => {
clearTimeout(typingTimer);
typingTimer = setTimeout(liveSearch, typeInterval);
});
function blogFilter() {
if (document.querySelector("#tag-select") !== null) {
let blog_div = document.getElementById("blogs");
let blogTagSelect = document.querySelector("#tag-select");
let selectedItem = blogTagSelect.options[blogTagSelect.selectedIndex];
if (selectedItem.innerText == "Tags") {
blog_div.innerHTML = "";
for (let i = 0; i < allBlogs.length; i++) {
let bootstrapDiv = document.createElement("div");
bootstrapDiv.classList = "col-lg-4 col-md-6 col-sm-12";
let card = document.createElement("div");
card.classList = "blog-listing__card";
let cardImage = document.createElement("div");
cardImage.classList = "blog-listing__card__image";
let link = document.createElement("a");
link.setAttribute("href", "#");
let img = document.createElement("img");
img.setAttribute("src", "./Bitmap.svg");
let cardText = document.createElement("div");
cardText.classList = "blog-listing__card__text";
let cardTitle = document.createElement("h2");
cardTitle.innerText = `Naslov ${i}`;
let textLink = document.createElement("a");
textLink.setAttribute("href", "#");
textLink.innerText = `Datum | Autor`;
let textText = document.createElement("p");
textText.innerText = `Opis`;
let topics = document.createElement("div");
topics.classList = "blog-listing__card__topics";
let topicList = document.createElement("ul");
let topicLi = document.createElement("li");
let topicLink = document.createElement("a");
topicLink.setAttribute("href", "#");
topicLink.innerText = `Tagovi`;
let divider = document.createElement("div");
divider.classList = "blog-listing__card__divider";
cardText.appendChild(cardTitle);
cardText.appendChild(textLink);
cardText.appendChild(textText);
link.appendChild(img);
cardImage.appendChild(link);
topicLi.appendChild(topicLink);
topicList.appendChild(topicLi);
topics.appendChild(topicList);
card.appendChild(cardImage);
card.appendChild(cardText);
card.appendChild(topics);
card.appendChild(divider);
bootstrapDiv.appendChild(card);
blog_div.appendChild(bootstrapDiv);
}
} else {
blog_div.innerHTML = "";
for (let i = 0; i < allBlogs.length; i++) {
if (allBlogs[i].topic.includes(selectedItem.innerText)) {
let bootstrapDiv = document.createElement("div");
bootstrapDiv.classList = "col-lg-4 col-md-6 col-sm-12";
let card = document.createElement("div");
card.classList = "blog-listing__card";
let cardImage = document.createElement("div");
cardImage.classList = "blog-listing__card__image";
let link = document.createElement("a");
link.setAttribute("href", "#");
let img = document.createElement("img");
img.setAttribute("src", "./Bitmap.svg");
let cardText = document.createElement("div");
cardText.classList = "blog-listing__card__text";
let cardTitle = document.createElement("h2");
cardTitle.innerText = `Naslov ${i}`;
let textLink = document.createElement("a");
textLink.setAttribute("href", "#");
textLink.innerText = `Datum | Autor`;
let textText = document.createElement("p");
textText.innerText = `Opis`;
let topics = document.createElement("div");
topics.classList = "blog-listing__card__topics";
let topicList = document.createElement("ul");
let topicLi = document.createElement("li");
let topicLink = document.createElement("a");
topicLink.setAttribute("href", "#");
topicLink.innerText = `Tagovi`;
let divider = document.createElement("div");
divider.classList = "blog-listing__card__divider";
cardText.appendChild(cardTitle);
cardText.appendChild(textLink);
cardText.appendChild(textText);
link.appendChild(img);
cardImage.appendChild(link);
topicLi.appendChild(topicLink);
topicList.appendChild(topicLi);
topics.appendChild(topicList);
card.appendChild(cardImage);
card.appendChild(cardText);
card.appendChild(topics);
card.appendChild(divider);
bootstrapDiv.appendChild(card);
blog_div.appendChild(bootstrapDiv);
}
}
}
}
}
// blogTagSelect.addEventListener("change", blogFilter);
https://i.stack.imgur.com/M3H2N.png
I tried to optimise the code to work for all numbers of pages but I can't find a good solution
For the pagination numbers and links, try something like this:
//Element to append page numbers
let paginationElem = document.getElementbyId("yourPageElementIdHere")
//Your blogs
let allBlogs = []
//Get number of pages required
let pagesNeeded = allBlogs.length / <number of entries per-page> //May need to be rounded
//Create numbered link for each page. Begin loop at 0 to avoid printing first page as "0"
for(i=1; i < pagesNeeded + 1; i++) {
let pageNum = document.createElement("a").innerHTML = i
pageNum.html = "" //your link to page here
paginationElem.append(pageNum)
}
In case you're wondering how to select and display the relevant articles on each page, you'll need to get the clicked number of the page - as search param (?pageNum=4) in link, perhaps - then create a loop, which will store the correct articles in an array. Something like this should work:
//Your articles in an array
let allBlogs = []
let pageNum = //Get value from search param
// Array for articles to display on desired page
let articlesToDisplay = []
//Set default for first page
let firstArticle = 0
// Set number of first article/starting point for loop
if(pageNum != 0) {
firstArticle = (pageNum - 1) * 10 //or other number of articles per page
}
// Loop through articles, beginning at first article,for desired number of articles (10, here). Push into array.
for(i=firstArticle; i < firstArticle + 10; i++) {
articles.push(allBlogs[i])
}
You can loop through the articlesToDislay array, or create elements in the final loop and have these appended to somewhere in the document.
Assuming we are adding items inside the cart and we have an icon displaying us how many items we added so far, and before proceeding to checkout we realize we want or need to delete some of those items...
do we use the .remove property for this task and we loop all the items inside the cart?
i realize how to remove the items row from the cart but how do i proceed if i want the icon to also display correctly the amount of items that are still inside the cart?
if (document.readyState == 'loading') {
document.addEventListener('DOMContentLoaded', ready)
} else {
ready()
}
function ready() {
var addToCartButtons = document.getElementsByClassName('button-4')
for (var i = 0; i < addToCartButtons.length; i++) {
var button = addToCartButtons[i]
button.addEventListener('click', addToCartClicked)
}
var removeCartItemButtons = document.getElementsByClassName('remove_button')
//loop through the buttons inside cart
for (var i = 0; i < removeCartItemButtons.length; i++) {
// specifies the button with are targeting
var button = removeCartItemButtons[i]
// button reacts to the click event
button.addEventListener('click', removeCartItem)
}
}
function addToCartClicked(event) {
var button = event.target
var itemCount = document.getElementsByClassName('total-qty')[0].innerText
for (var i = 0; i < itemCount.length; i++) {
console.log(itemCount)
var itemCount = document.getElementsByClassName('total-qty')[i];
itemCount.innerText=parseInt(itemCount.innerText)+1;
}
}
function removeCartItem(event) {
var buttonClicked = event.target
buttonClicked.parentElement.parentElement.remove()
}
https://jsfiddle.net/sigurd14/pmLzt23h/52/
You can simply use querySelector method and set the innerText to 0 in your remove() function to decrease (reset) your counter back to its original state which is 0
Live Demo:
if (document.readyState == 'loading') {
document.addEventListener('DOMContentLoaded', ready)
} else {
ready()
}
function ready() {
var addToCartButtons = document.getElementsByClassName('button-4')
for (var i = 0; i < addToCartButtons.length; i++) {
var button = addToCartButtons[i]
button.addEventListener('click', addToCartClicked)
}
var removeCartItemButtons = document.getElementsByClassName('remove_button')
//loop through the buttons inside cart
for (var i = 0; i < removeCartItemButtons.length; i++) {
// specifies the button with are targeting
var button = removeCartItemButtons[i]
// button reacts to the click event
button.addEventListener('click', removeCartItem)
}
}
function addToCartClicked(event) {
var button = event.target
var itemCount = document.getElementsByClassName('total-qty')[0].innerText
for (var i = 0; i < itemCount.length; i++) {
//console.log(itemCount)
var itemCount = document.getElementsByClassName('total-qty')[i];
itemCount.innerText = parseInt(itemCount.innerText) + 1;
}
}
function removeCartItem(event) {
var buttonClicked = event.target
var qty = document.querySelector('.total-qty')
qty.innerText = 0
}
.total-qty {
position: absolute;
height: 1.5rem;
width: 1.5rem;
background: #4312f2;
color: white;
border-radius: 50%;
border: 1px solid #4312f2;
text-align: center;
line-height: 1rem;
font-weight: 600;
top: 0.3rem;
right: 0.3rem;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.remove_button {
padding: 0;
background-color: transparent;
color: #2a10ee;
align-self: start;
}
<button class="button-4">+</button>
<div>
<span class="total-qty">0</span>
<button class="remove_button w-button" type="button">Remove</button>
</div>
you need to add a remove button for each item in your cart.
if (document.readyState == 'loading') {
document.addEventListener('DOMContentLoaded', ready)
} else {
ready()
}
function ready() {
var cart = document.getElementById('cart');
var addToCartButtons = document.getElementsByClassName('button-4')
for (var i = 0; i < addToCartButtons.length; i++) {
var button = addToCartButtons[i]
button.addEventListener('click', addToCartClicked)
}
var removeCartItemButtons = document.getElementsByClassName('remove_button')
//loop through the buttons inside cart
for (var i = 0; i < removeCartItemButtons.length; i++) {
// specifies the button with are targeting
var button = removeCartItemButtons[i]
// button reacts to the click event
button.addEventListener('click', removeCartItem)
}
}
function addToCartClicked(event) {
var itemCount = document.getElementsByClassName('item');
var newItem = createNewCartItem(itemCount.length+1);
cart.append(newItem);
updateCounter();
}
function createNewCartItem(item){
var newItem =document.createElement('div');
newItem.classList.add('item');
var textWrapper = document.createElement('span');
textWrapper.innerText = item;
var removeBtn = createRemoveBtn();
newItem.append(textWrapper);
newItem.append(removeBtn);
return newItem;
}
function createRemoveBtn(){
var btn = document.createElement('button');
btn.innerText = 'remove';
btn.addEventListener('click', function(){
this.parentNode.remove();
updateCounter();
});
return btn;
}
function updateCounter(){
var counter = document.getElementById('total-qty');
var itemCount = document.getElementsByClassName('item');
counter.innerText = itemCount.length;
}
.total-qty {
position: absolute;
height: 1.5rem;
width: 1.5rem;
background: #4312f2;
color: white;
border-radius: 50%;
border: 1px solid #4312f2;
text-align: center;
line-height: 1rem;
font-weight: 600;
top: 0.3rem;
right: 0.3rem;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.remove_button {
padding: 0;
background-color: transparent;
color: #2a10ee;
align-self: start;
}
<button class="button-4">+</button>
<div>
<span id="total-qty" class="total-qty">0</span>
</div>
<div id="cart">
</div>
I'm creating a grid 16x16 with javascript. I also want the grid to do something when the mouse hover over each square. The problem is that I do not know how to add a class in a iterative way that every div get the same class.
Doing so, I would make jQuery do the action with one function applied to that class.
This is my present code
var contador = 1;
var outra = document.createElement('div');
outra.id = 'container';
document.body.appendChild(outra);
for (i=1;i<=16;i++){
for (j=1;j<=16;j++){
var divCreation = document.createElement('div');
var created = divCreation;
created.id = "numero"+ contador;
console.log(created.id);
created.textContent = ". ";
contador = contador + 1;
outra.appendChild(created);
}
}
$('#numero'+contador).hover(function(){
$(this).css('background-color','yellow');
});
If you want to give a specific class to your dynamically created elements, you can do it using className property.
Your code would be like this:
divCreation.className = "someClass";
Note:
I don't see why you are setting divCreation in a new variable, it's
just useless.
And instead of detecting hover with jQuery, you can just do it with css, look at my Demo below, or if you want to keep jquery you can use the class selector like this $('.box').hover(...).
Demo:
var outra = document.createElement('div');
outra.id = 'container';
var contador = 1;
document.body.appendChild(outra);
for (i = 1; i <= 16; i++) {
for (j = 1; j <= 16; j++) {
var created = document.createElement('div');
created.className = "box";
created.id = "numero" + contador;
created.textContent = ". ";
contador++;
outra.appendChild(created);
}
}
.box:hover {
background-color: yellow;
}
No need for use of ID for this at all...just use a common class. Also since using jQuery can create all this with a lot less code using by using it.
var $outra = $('<div>', { id: 'container'});
for (i = 1; i <= 16; i++) {
for (j = 1; j <= 16; j++) {
$outra.append( $('<div>', { class: 'box', text: '.'}) );
}
}
$('body').append($outra);
$('.box').hover(function() {
$(this).toggleClass('yellow');
});
.box {
width: 50px;
height: 50px;
display: inline-block;
border: 1px solid #ccc
}
.box.yellow {
background-color: yellow
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can use the attribute starts with selector
$('[id^=numero').hover(
or provide a class to the element and target the elements using the class
This will select all the elements whose id starts with the value you are specifying and attach a hover event.
And when you are using jQuery, why do you want to mix in both Vanilla JS and jQuery. You can just stick with one.
var contador = 1;
var $outra = $('<div/>', {
id: 'container',
class: 'container'
});
$('body').append($outra);
for (i=1;i<=16;i++){
for (j=1;j<=16;j++) {
var $divCreation = $('<div/>', {
id: 'numero' + contador,
text: '. ',
class: 'box'
});
$outra.append($divCreation);
contador = contador + 1;
}
}
$('[id^=numero').hover(function(){
$(this).css('background-color','yellow');
});
.container {
width: 200px;
height: 200px;
border: 1px solid green;
}
.box {
width: 20px;
height: 20px;
border: 1px solid black;
background: green;
float: left;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I want to link a button with div dynamically using id’s for example.
I have two buttons and two div this is been dynamically created if i click the second button it has to go second div if i click first button it first button has to visible. Using pure vanila javascript.
var inputElement = document.getElementById("inputAdd_page");
var totalCount = 0;
inputElement.addEventListener('blur', function() {
var count = this.value;
if(count && !isNaN(count)) {
fragment = document.createDocumentFragment();
for (var j = 0; j < count; ++j) {
spancount = document.createElement('span');
prevPage = document.createElement('div');
navbutton = document.createElement('button');
preview_PageSize = document.getElementById('page');
navpageBtn = document.getElementById('pageBtn');
navbutton.className = "div_navig";
navbutton.setAttribute('id', ['pag_navg' + totalCount]);
navbutton.innerHTML=[1 + totalCount];
spancount.className = "spanCount";
spancount.innerHTML=[1 + totalCount];
prevPage.className = "preview_windowSize_element";
prevPage.setAttribute('id', ['page' + (totalCount)]);
prevPage.appendChild(spancount);
navpageBtn.appendChild(navbutton);
prevPage.setAttribute('id', ['page' + (totalCount)]);
preview_PageSize.childNodes[0]);
totalCount++;
}
inputElement.value="";
document.body.appendChild(fragment);
}
});
Here is the fiddle Link
Kindly help me actually I am trying I am not getting it
Thanks in advance
I would suggest not using a partial id or anything like that to link your elements. Instead, use an attribute specifically created for the purpose. In the following code, I'm using an attribute named data-page which is simply set to the value you're appending to the ids. I also added an event handler which just sets the z-index of all pages to 0, then sets the selected page's z-index to 10.
//create div
var inputElement = document.getElementById("inputAdd_page");
var totalCount = 0;
inputElement.addEventListener('blur', function() {
var count = this.value;
// Gaurd condition
// Only if it is a number
if (count && !isNaN(count)) {
fragment = document.createDocumentFragment();
for (var j = 0; j < count; ++j) {
spancount = document.createElement('span');
prevPage = document.createElement('div');
navbutton = document.createElement('button');
preview_PageSize = document.getElementById('page');
navpageBtn = document.getElementById('pageBtn');
navbutton.className = "div_navig";
navbutton.setAttribute('id', ['pag_navg' + totalCount]);
navbutton.setAttribute('data-page', totalCount);
navbutton.innerHTML = [1 + totalCount];
navbutton.addEventListener('click', function (e) {
var el = e.target;
var page = parseInt(el.getAttribute('data-page'), 10);
var allPages = document.querySelectorAll('.preview_windowSize_element');
Array.prototype.forEach.call(allPages, function (pageElement) {
pageElement.style.zIndex = 0;
});
var pageEl = document.querySelector('div[data-page="' + page + '"]');
pageEl.style.zIndex = 10;
});
spancount.className = "spanCount";
spancount.innerHTML = [1 + totalCount];
prevPage.className = "preview_windowSize_element";
prevPage.setAttribute('id', ['page' + (totalCount)]);
prevPage.setAttribute('data-page', totalCount);
prevPage.appendChild(spancount);
navpageBtn.appendChild(navbutton);
preview_PageSize.insertBefore(prevPage, preview_PageSize.childNodes[0]);
totalCount++;
}
inputElement.value = "";
document.body.appendChild(fragment);
}
});
.title_Textbox {
border: 1px solid rgb(152, 152, 152);
width: 230px;
padding: 5px 0 5px 5px;
}
.preview_windowSize {
margin: 15px 15px 15px 15px;
height: 300px;
padding: 5px;
}
.preview_windowSize_element {
position: absolute;
background-color: lightGrey;
border: 1px solid rgb(155, 155, 155);
border-bottom-right-radius: 10px;
border-bottom-left-radius: 10px;
padding: 5px;
width: 93.5%;
height: 300px;
}
<input type="text" class="form-control title_Textbox" id="inputAdd_page" placeholder="No Of Pages">
<div class="preview_windowSize" id="page">
</div>
<div id="pageBtn" class="row pagination_btn">
</div>
I am trying to append / (Bind) textbox innerhtml value to the dynamic div which has the pagination. When I am trying append with textbox with the div I am getting an error.
There are two elements in my initial page First One is for no of pages and other one is for enter some text. If I enter number 2 so two div will appear dynamically. Then I enter the greeting text second text box. Text should appear in the first div and for the second div if i click the button in the bottom second div should be empty. Using Pure javascript (Vanila).
I am trying to get value from the textbox. But I was not able to bind with the p tag which was available dynamically.
Kindly help me.
var gettext_Title = document.getElementById('title_Text')
var getresult = gettext_Title.value;
//alert(result);
var inputElement = document.getElementById("inputAdd_page");
var totalCount = 0;
inputElement.addEventListener('blur', function() {
var count = this.value;
// Gaurd condition
// Only if it is a number
if (count && !isNaN(count)) {
fragment = document.createDocumentFragment();
for (var j = 0; j < count; ++j) {
spancount = document.createElement('span');
prevPage = document.createElement('div');
navbutton = document.createElement('button');
hTitle = document.createElement('p');
preview_PageSize = document.getElementById('page');
navpageBtn = document.getElementById('pageBtn');
navbutton.className = "div_navig";
navbutton.setAttribute('id', ['pag_navg' + totalCount]);
navbutton.setAttribute('data-page', totalCount);
navbutton.innerHTML = [1 + totalCount];
navbutton.addEventListener('click', function (e) {
var el = e.target;
var page = parseInt(el.getAttribute('data-page'), 10);
var allPages = document.querySelectorAll('.preview_windowSize_element');
Array.prototype.forEach.call(allPages, function (pageElement) {
pageElement.style.zIndex = 0;
});
var pageEl = document.querySelector('div[data-page="' + page + '"]');
pageEl.style.zIndex = 10;
});
spancount.className = "spanCount";
spancount.innerHTML = [1 + totalCount];
hTitle.setAttribute('id', ['Title' + (totalCount)]);
hTitle.className = "title_boundry";
prevPage.className = "preview_windowSize_element";
prevPage.setAttribute('id', ['page' + (totalCount)]);
prevPage.setAttribute('data-page', totalCount);
prevPage.appendChild(spancount);
prevPage.appendChild(hTitle);
navpageBtn.appendChild(navbutton);
preview_PageSize.insertBefore(prevPage, preview_PageSize.childNodes[0]);
totalCount++;
}
inputElement.value = "";
document.body.appendChild(fragment);
}
});
Here is the Jsfiddle Link
Thanks in advance
Kindly help me
Cheers,
If I understand correctly what you mean, try this:
main.js :
(function () {
var inputTitle,
inputElement,
current,
totalCount = 0;
document.addEventListener('DOMContentLoaded', function (e) {
inputTitle = document.getElementById('title_Text');
inputElement = document.getElementById("inputAdd_page");
inputElement.addEventListener('blur', onInputElementBlur);
inputTitle.addEventListener('blur', onInputTitleBlur);
});
function onInputTitleBlur(e) {
if (!!current) {
var title = current.querySelector('p');
title.innerText = inputTitle.value;
inputTitle.value = '';
}
}
function onInputElementBlur() {
var count = this.value;
// Gaurd condition
// Only if it is a number
if (count && !isNaN(count)) {
var fragment = document.createDocumentFragment();
for (var j = 0; j < count; ++j) {
var spancount = document.createElement('span');
var prevPage = document.createElement('div');
var navbutton = document.createElement('button');
var hTitle = document.createElement('p');
var preview_PageSize = document.getElementById('page');
var navpageBtn = document.getElementById('pageBtn');
navbutton.className = "div_navig";
navbutton.setAttribute('id', 'pag_navg' + totalCount);
navbutton.setAttribute('data-page', totalCount);
navbutton.innerHTML = 1 + totalCount;
navbutton.addEventListener('click', function (e) {
var el = e.target;
var page = parseInt(el.getAttribute('data-page'), 10);
var allPages = document.querySelectorAll('.preview_windowSize_element');
Array.prototype.forEach.call(allPages, function (pageElement) {
pageElement.style.zIndex = 0;
});
var pageEl = document.querySelector('div[data-page="' + page + '"]');
current = pageEl;
pageEl.style.zIndex = 10;
});
spancount.className = "spanCount";
spancount.innerHTML = 1 + totalCount;
hTitle.setAttribute('id', 'Title' + (totalCount));
hTitle.className = "title_boundry";
prevPage.className = "preview_windowSize_element";
prevPage.setAttribute('id', 'page' + (totalCount));
prevPage.setAttribute('data-page', totalCount);
prevPage.appendChild(spancount);
prevPage.appendChild(hTitle);
navpageBtn.appendChild(navbutton);
preview_PageSize.insertBefore(prevPage, preview_PageSize.childNodes[0]);
totalCount++;
}
current = document.querySelector('div[data-page="0"]');
inputElement.value = "";
document.body.appendChild(fragment);
}
}
}());
index.html :
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<link id="myStyleSheet" href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<input type="text" class="form-control title_Textbox" id="title_Text" placeholder="Text">
<input type="text" class="form-control title_Textbox" id="inputAdd_page" placeholder="No Of Pages">
<div class="preview_windowSize" id="page"></div>
<div id="pageBtn" class="row pagination_btn"></div>
<script src="main.js" type="text/javascript"></script>
</body>
</html>
style.css :
.div_navig {
background: lightGrey;
width: 24px;
height: 24px;
text-align: center;
margin-left: 5px;
color: black;
cursor: pointer;
}
.pagination_btn {
float: right;
margin: 0 20px 0 0;
padding-left: 5px;
}
.spanCount {
position: absolute;
bottom: 0;
right: 0;
padding: 0 10px 0 5px;
}
.preview_windowSize {
margin: 15px 15px 15px 15px;
height: 300px;
padding: 5px;
}
.preview_windowSize_element {
position: absolute;
background-color: lightGrey;
border: 1px solid rgb(155, 155, 155);
border-bottom-right-radius: 10px;
border-bottom-left-radius: 10px;
padding: 5px;
width: 93.5%;
height: 300px;
}
.title_boundry {
border: 1px dotted #000;
height: 40px;
}