javascript - display in a random order everytime page is refreshed - javascript

What should I do to make this display in a random order every time the page is refreshed.
here's what I added on my WordPress text editor and it displays the images perfectly fine but it does not randomize the order of the divs. What did I do wrong?
<br><br>
<div class="quiz">
<a href="http://www.thequizmania.com/we-bet-you-cant-pass-this-tricky-general-knowledge-quiz/">
<img src="http://i.imgur.com/3YcBoyN.jpg"></img>
<a>
</div>
<br>
<div class="quiz">
<a href="http://www.thequizmania.com/what-kind-of-traveler-are-you/">
<img src="http://i.imgur.com/GZn9myC.jpg"></img>
<a>
</div>
<br>
<div class="quiz">
<a href="http://www.thequizmania.com/what-two-words-describe-you-as-a-mother/">
<img src="http://i.imgur.com/QnJezBF.jpg"></img>
<a>
</div>
<br>
<div class="quiz">
<a href="http://www.thequizmania.com/can-you-pick-the-correct-word/">
<img src="http://i.imgur.com/Pdi9dyo.jpg"></img>
<a>
</div>
<br>
<div class="quiz">
<a href="http://www.thequizmania.com/can-you-pass-this-almost-impossible-shapes-test/">
<img src="http://i.imgur.com/Ov5WdOg.jpg"></img>
<a>
</div>
<br>
<script>
var cards = $(".quiz");
for(var i = 0; i < cards.length; i++){
var target = Math.floor(Math.random() * cards.length -1) + 1;
var target2 = Math.floor(Math.random() * cards.length -1) +1;
cards.eq(target).before(cards.eq(target2));
}
</script>

Your code works fine.
I just:
Fixed <a> tag
Added Jquery library
Here your code on Jsfiddle

You can randomize it with Math.random.
var divContents = ['<br><div class="quiz"><img src="http://i.imgur.com/Ov5WdOg.jpg"></div>', 'second', 'thrid', '4th', '5th', '6th'];
var len = divContents.length;
var parent = document.getElementById('parent');
for(i=0;i<len;i++) {
var random = Math.floor(Math.random()*(divContents.length));
parent.innerHTML += (divContents[random]);
divContents.splice(random, 1);
}
<div id="parent">
</div>

Related

Amp-script does not show the result for addEventListener "load"

I want to copy all A to B. Using plain javascript, it works as it is. But it does not work when I use amp-script. It also doesn't show any error(s).
A
<div class="harga">111</div>
<div class="harga">222</div>
<div class="harga">333</div>
B
<div class="showHargaProd"></div>
<div class="showHargaProd"></div>
<div class="showHargaProd"></div>
Javascript
<script>
function getAndShow(){
let sources = document.querySelectorAll('.harga');
let dests = document.querySelectorAll('.showHargaProd');
for (let i = 0; i < sources.length; i++){
if (dests[i]){
dests[i].innerHTML = sources[i].innerHTML;
}
}
}
document.addEventListener('DOMContentLoaded', getAndShow);
</script>
Here's all my codes
<amp-script layout='container' script='inline_amp'>
<div class='container_slide'>
<div class='prod_price'><b class='showHargaProd'><!--111--></b></div>
<div class='overlay'>
<div class='text'><b>BELI</b></div>
</div>
</div>
<div class='container_slide'>
<div class='prod_price'><b class='showHargaProd'><!--222--></b></div>
<div class='overlay'>
<div class='text'><b>BELI</b></div>
</div>
</div>
<div class='container_slide'>
<div class='prod_price'><b class='showHargaProd'><!--333--></b></div>
<div class='overlay'>
<div class='text'><b>BELI</b></div>
</div>
</div>
<p id="hrg1" class="harga">111</p>
<p id="hrg2" class="harga">222</p>
<p id="hrg3" class="harga">333</p>
</amp-script>
<script id="inline_amp" type="text/plain" target="amp-script">
function getAndShow(){
let sources = document.querySelectorAll('.harga');
let dests = document.querySelectorAll('.showHargaProd');
for (let i = 0; i < sources.length; i++){
if (dests[i]){
dests[i].innerHTML = sources[i].innerHTML;
}
}
}
document.addEventListener('DOMContentLoaded', getAndShow);
</script>
Finally I use time (seconds) to trigger the DOM, as in:
HTML
<input id='nTrigger' name='nTrigger' type='hidden' value='0'/>
<input id='nCheck' name='nCheck' type='hidden' value=''/>
JS
var dy = new Date();
var n = dy.getSeconds();
var trig = document.getElementById('nTrigger').value;
document.getElementById('nCheck').value = n;
if (trig !== n) getAndShow();
Here's trig would never equal as n forever since seconds has no zero value and it will show the result I wish.
Stupid of me, I actually can use directly or call function getAndShow() when the layout is responsive with fixed height and width (size must be included).
What I want is how to load the class showHargaProd when user load the page, and It solved successfully.
Here's all the codes:
Note: layout='container' must be changed into layout='responsive' (see issue in related to layout system and gestures: https://github.com/ampproject/amphtml/issues/28361#issuecomment-628779575) and How to show popup on AMP page after setTimeout
Or, we can use flex-item Layout to make it properly in container
<amp-script layout='flex-item' script='inline_amp'>
<div class='container_slide'>
<div class='prod_price'><b class='showHargaProd'><!--111--></b></div>
<div class='overlay'>
<div class='text'><b>BELI</b></div>
</div>
</div>
<div class='container_slide'>
<div class='prod_price'><b class='showHargaProd'><!--222--></b></div>
<div class='overlay'>
<div class='text'><b>BELI</b></div>
</div>
</div>
<div class='container_slide'>
<div class='prod_price'><b class='showHargaProd'><!--333--></b></div>
<div class='overlay'>
<div class='text'><b>BELI</b></div>
</div>
</div>
<p id="hrg1" class="harga">111</p>
<p id="hrg2" class="harga">222</p>
<p id="hrg3" class="harga">333</p>
<input id='nTrigger' name='nTrigger' type='hidden' value='0'/>
<input id='nCheck' name='nCheck' type='hidden' value=''/>
</amp-script>
<script id="inline_amp" type="text/plain" target="amp-script">
function getAndShow(){
let sources = document.querySelectorAll('.harga');
let dests = document.querySelectorAll('.showHargaProd');
for (let i = 0; i < sources.length; i++){
if (dests[i]){
dests[i].innerHTML = sources[i].innerHTML;
}
}
}
//document.addEventListener('DOMContentLoaded', getAndShow);
var dy = new Date();
var n = dy.getSeconds();
var trig = document.getElementById('nTrigger').value;
document.getElementById('nCheck').value = n;
if (trig !== n) getAndShow();
</script>
More: (trig !== n) in fact, it would never equal and therefore, it triggers the function getAndShow() (that is almost the same as DOMContentLoaded).

JavaScript Uncaught TypeError - Shopping Cart Total

I'm finishing the project and I'm struggling with couple things:
1 Shopping Cart in javascript
I expected <p class="subTotal">$ 0</p> to update after adding, or deleting elements from the shopping cart. Instead, when I add element to the shopping cart, p.subTotal updates 2x the price of dish.
The next one is deleting elements from the shopping cart. When I do that, the console return this:
Console screenshot #1
2 Removing the object
To remove object from the shopping cart I had to select parent of the parent of the button.
Inside the button I've put the svg icon. Somehow, when I click on svg icon, javascript code selects parent of the parent of the svg instead of the button's.
3 Adding dishes to the shopping cart
I've put <a href="#" class="addToCart"> inside of <div class="food">.
This action results in console, showing me another error:
Console screenshot #2
If You can answer even one question I will really appreciate that.
I have only few hours left to finish it.
Code:
if (document.readyState == 'loading') {
document.addEventListener('DOMContentLoaded', ready);
} else {
ready();
}
function ready() {
var removeCartItemButtons = document.getElementsByClassName('trash');
for (var i = 0; i < removeCartItemButtons.length; i++) {
var button = removeCartItemButtons[i];
button.addEventListener('click', removeCartItem);
}
var quantityInputs = document.getElementsByClassName('quantity');
for (var i = 0; i < quantityInputs.length; i++) {
var input = quantityInputs[i];
input.addEventListener('change', quantityChanged);
}
var addToCart = document.getElementsByClassName('addToCart');
for (var i = 0; i < addToCart.length; i++) {
var button = addToCart[i];
button.addEventListener('click', addToCartClicked);
}
}
function removeCartItem(event) {
var buttonClicked = event.target;
buttonClicked.parentElement.parentElement.remove();
updateCartTotal();
}
function quantityChanged(event) {
var input = event.target;
if (isNaN(input.value) || input.value <= 0) {
input.value = 1;
}
updateCartTotal();
}
function addToCartClicked(event) {
var button = event.target;
var shopItem = button.parentElement;
var title = shopItem.getElementsByClassName('name')[0].innerText;
var price = shopItem.getElementsByClassName('price')[0].innerText;
var imageSrc = shopItem.getElementsByClassName('foodImg')[0].src;
addItemToCart(title, price, imageSrc);
updateCartTotal();
}
function addItemToCart(title, price, imageSrc) {
var product = document.createElement('div');
product.classList.add('product');
var basket = document.getElementsByClassName('basket')[0];
var productContents = `
<div class="product">
<div class="productInfo">
<div class="productName">
<img src="${imageSrc}" alt="Spicy seasoned seafood noodles">
<div>
<p class="productTitle">${title}</p>
<p class="money">${price}</p>
</div>
</div>
<input class="quantity" type="text" value="1">
<p class="cash">${price}</p>
</div>
<div class="note">
<input type="text" placeholder="Order Note...">
<button class="trash"><svg width="24" height="24" viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg">
<path
d="M18.8789 8.71882L18.9784 8.72017C19.3475 8.75069 19.6304 9.05716 19.65 9.42605L19.6405 9.63174L19.326 13.483L18.9961 17.2414C18.9263 17.9917 18.8638 18.6245 18.8099 19.1227C18.6225 20.8588 17.4955 21.9323 15.7966 21.9641C13.1494 22.013 10.6048 22.0125 8.13373 21.9591C6.48398 21.9244 5.37366 20.8393 5.18955 19.1297L5.0623 17.8702L4.83994 15.427L4.61216 12.7461L4.35172 9.52788C4.31935 9.11498 4.61951 8.75335 5.02215 8.72016C5.39123 8.68973 5.7183 8.94584 5.79519 9.30677L5.82511 9.60173L6.06966 12.6187L6.33669 15.7459C6.45646 17.0996 6.56034 18.1952 6.64346 18.9648C6.74838 19.939 7.26138 20.4404 8.16411 20.4593C10.6159 20.5124 13.1415 20.5129 15.7701 20.4643C16.7277 20.4464 17.2488 19.9499 17.356 18.9574L17.4827 17.7046C17.5198 17.3185 17.5594 16.8923 17.6013 16.4293L17.8686 13.3538L18.1906 9.4075C18.2204 9.02902 18.5192 8.7389 18.8789 8.71882ZM3.73139 6.98918C3.32745 6.98918 3 6.65338 3 6.23916C3 5.85945 3.27515 5.54564 3.63214 5.49597L3.73139 5.48913H6.91772C7.29636 5.48913 7.62785 5.23928 7.74642 4.87929L7.77543 4.76813L8.02304 3.50533C8.24111 2.66897 8.9492 2.07349 9.779 2.00633L9.93592 2H14.0639C14.9075 2 15.6523 2.54628 15.9391 3.39039L15.9874 3.55209L16.2243 4.76783C16.2987 5.14872 16.6025 5.4332 16.9701 5.48177L17.0821 5.48913H20.2686C20.6725 5.48913 21 5.82493 21 6.23916C21 6.61887 20.7248 6.93267 20.3679 6.98234L20.2686 6.98918H3.73139ZM14.0639 3.50006H9.93592C9.7307 3.50006 9.54829 3.62322 9.47252 3.77803L9.44682 3.84604L9.20979 5.06238C9.1808 5.21084 9.13879 5.3538 9.08512 5.49012L14.9148 5.49031C14.8813 5.40526 14.8523 5.31763 14.8282 5.22768L14.79 5.06208L14.5636 3.8928C14.5107 3.68991 14.3473 3.54138 14.1502 3.50742L14.0639 3.50006Z" />
</svg></button>
</div>
</div>`;
product.innerHTML = productContents;
basket.append(product);
product
.getElementsByClassName('trash')[0]
.addEventListener('click', removeCartItem);
product
.getElementsByClassName('quantity')[0]
.addEventListener('change', quantityChanged);
}
function updateCartTotal() {
var cartItemContainer = document.getElementsByClassName('basket')[0];
var products = cartItemContainer.getElementsByClassName('product');
var total = 0;
for (var i = 0; i < products.length; i++) {
var product = products[i];
var priceElement = product.getElementsByClassName('money')[0];
var quantityElement = product.getElementsByClassName('quantity')[0];
var price = parseFloat(priceElement.innerText.replace('$', ''));
var quantity = quantityElement.value;
total = total + price * quantity;
}
total = Math.round(total * 100) / 100;
document.getElementsByClassName('subTotal')[0].innerText = '$ ' + total;
}
// Date in header
var dt = new Date();
document.getElementById('datetime').innerHTML = dt.toLocaleDateString();
<div id="foodCard">
<div class="food">
<a href="#" class="addToCart">
<div class="bg">
<img class="foodImg" src="style/img/Image 1.png" alt="Spicy seasoned seafood noodles">
<div class="text">
<p class="name">Spicy seasoned seafood noodles</p>
<div>
<p class="price">$ 2.29</p>
<p class="availability">20 Bowls available</p>
</div>
</div>
</div>
</a>
</div>
<div class="food">
<a href="#" class="addToCart">
<div class="bg">
<img class="foodImg" src="style/img/Image 2.png" alt="Salted Pasta with mushroom sauce">
<div class="text">
<p class="name">Salted Pasta with mushroom sauce</p>
<div>
<p class="price">$ 2.69</p>
<p class="availability">11 Bowls available</p>
</div>
</div>
</div>
</a>
</div>
<div class="food">
<a href="#" class="addToCart">
<div class="bg">
<img class="foodImg" src="style/img/Image 3.png" alt="Beef dumpling in hot and sour soup">
<div class="text">
<p class="name">Beef dumpling in hot and sour soup</p>
<div>
<p class="price">$ 2.99</p>
<p class="availability">16 Bowls available</p>
</div>
</div>
</div>
</a>
</div>
<div class="food">
<a href="#" class="addToCart">
<div class="bg">
<img class="foodImg" src="style/img/Image 5.png" alt="Spicy seasoned seafood noodles">
<div class="text">
<p class="name">Spicy seasoned seafood noodles</p>
<div>
<p class="price">$ 2.29</p>
<p class="availability">20 Bowls available</p>
</div>
</div>
</div>
</a>
</div>
</div>
</div>
</div>
</main>
<section id="order">
<div id="container">
<header>
<h2>Orders #34562</h2>
<div id="selector">
<button class="active">Dine in</button>
<button>To Go</button>
<button>Delivery</button>
</div>
<div id="description">
<p>Item</p>
<p>Qty</p>
<p>Price</p>
</div>
</header>
<div class="basket">
</div>
<div id="bottom">
<div id="total">
<div id="discount">
<p>Discount</p>
<p>$0</p>
</div>
<div id="subTotal">
<p>Sub total</p>
<p class="subTotal">$ 0</p>
</div>
I couldn't have time to go through the full code, but I had an observation. document.getElementsByClassName('subTotal')[0].innerText = '$ ' + total;, is the getElementsByClassName('subTotal') returning a element or just returning undefined? Because, you can't access innerHTML from undefined.
Also, is shopItem.getElementsByClassName('foodImg')[0] not undefined? If it is undefined, then you will get src of undefined error. Is there an element with class name foodImg?

Pure Javascript display div based on Menu Item Clicked?

I just need some advice with my current code. I am trying to display a different div depending on the menu item clicked. I was thinking theoretically using some kind of indexing method. i think the if statement i am using for once does not work but also seems a little horrible in terms of coding.
anyway what do you think?
/**
* Lets get Menu container
*/
var menu = document.getElementById("configurator-menu");
/**
* Set Current Tab and Store which tab is Active
*/
var navitem = menu.querySelector(".configurator-menuitems div");
navitem.className += " " + "activeTab";
/**
* Add click events to Menu Tabs
*/
var tabs = menu.querySelectorAll(".configurator-menuitems div");
for (var i = 0; i < tabs.length; i++) {
tabs[i].onclick=displayPage;
}
/**
* Tabs Logic
*/
function displayPage() {
var items = menu.querySelectorAll(".configurator-menuitems div");
for (var i = 0; i < items.length; i++) {
items[i].classList.remove("activeTab");
}
this.className += " " + "activeTab";
if (this.classList.contains("mainMenu1")) {
var item = document.getElementByClassName("appCanvas1");
item.style.display = "block";
}
else if (this.classList.contains("mainMenu2")) {
var item = document.getElementByClassName("appCanvas2");
item.style.display = "block";
}
else if (this.classList.contains("mainMenu3")) {
var item = document.getElementByClassName("appCanvas3");
item.style.display = "block";
}
}
<div id="configurator-menu" class="appMenu" style="background-color:#001A35;">
<div class="appLogo">
Logo Here
</div>
<hr class="no-margin" />
<div class="configurator-menuitems">
<div class="mainMenu-btn mainMenu1">Shape</div><hr class="no-margin" />
<div class="mainMenu-btn mainMenu2">Size</div><hr class="no-margin" />
<div class="mainMenu-btn mainMenu3">Color</div><hr class="no-margin" />
</div>
<div class="menuspacer"></div><hr class="no-margin" />
<div class="currentSettings">
<p class="settings-title">Your Selection</p>
<p class="variant-config">Shape: </p>
<p class="variant-config">Colors: </p>
<p class="variant-config">Size: </p>
<p class="variant-config">Quantity: </p>
<p class="variant-config">Total Price: </p>
</div>
</div>
<div class="canvas-wrapper">
<div class="appCanvas1" style="background-color:#e7e7e7;">
<div class="shape-selection-bar">
<div class="shape-selector"><img src="'.plugins_url("pentant_conical.png", __FILE__).'" alt="" /></div>
<div class="shape-selector"><img src="'.plugins_url("pendant_cyl.png", __FILE__).'" alt="" /></div>
<div class="shape-selector"><img src="'.plugins_url("standing_lamp_conical.png", __FILE__).'" alt="" /></div>
<div class="shape-selector"><img src="'.plugins_url("standing_lamp_cyl.png", __FILE__).'" alt="" /></div>
</div>
<div class="configurator-progressBtn"> Move On</div>
</div>
<div class="appCanvas2" style="background-color:#e7e7e7;">
<div class="configurator-progressBtn"> Move On</div>
</div>
<div class="appCanvas3" style="background-color:#e7e7e7;">
<div class="configurator-progressBtn"> Move On</div>
</div>
</div>

Javascript select div and change href inside

I am trying to modify the links in my page using JavaScript. I can select the div and the a element but cannot change the href.
Shopify is using a for loop to generate these objects and need each object to have a different link.
Here is the HTML:
<div id="tri-banner-1" class="banner-element banner-1 col-sm-4">
<a href="collections/all"><div class="home-banner">
<img src='//cdn.shopify.com/s/files/1/1093/4220/t/2/assets/group_top_banner01.png?17711418137279289271' alt="">
<div class="banner-caption">
<div class="display-table">
<div class="display-tablecell">
</div>
</div>
</div>
</div></a>
</div>
<div id="tri-banner-2" class="banner-element banner-2 col-sm-4">
<a href="collections/all"><div class="home-banner">
<img src='//cdn.shopify.com/s/files/1/1093/4220/t/2/assets/group_top_banner02.png?17711418137279289271' alt="">
<div class="banner-caption">
<div class="display-table">
<div class="display-tablecell">
</div>
</div>
</div>
</div></a>
</div>
<div id="tri-banner-3" class="banner-element banner-3 col-sm-4">
<a href="collections/all"><div class="home-banner">
<img src='//cdn.shopify.com/s/files/1/1093/4220/t/2/assets/group_top_banner03.png?17711418137279289271' alt="">
<div class="banner-caption">
<div class="display-table">
<div class="display-tablecell">
</div>
</div>
</div>
</div></a>
</div>
Here is my JavaScript.
<script type="text/javascript">
$(window).bind("load", function() {
window.alert("Test");
var banner1 = document.getElementById("tri-banner-1");
var banner1Links = banner1.getElementsByTagName("a");
banner1Links.href="facebook.com";
});
</script>
banner1.getElementsByTagName("a"); returns an HTMLCollection . You should either select the element using the index ; e.g.;
// set `href` of first `a` element in `bannerLinks`
banner1Links[0].href = "facebook.com";
or iterate the collection
for (var i = 0; i < bannerLinks.length; i++) {
bannerLinks[i] = /* set `href` here */;
}
banner1Links gets an array value so you need to loop in that array and for every array element you pass the value
// instead of banner1Links.href="facebook.com";
for(var i = 0; i < banner1Links.length; i += 1){
banner1Links[i] = 'http://example.com';
}

Wrapping an anchor tag around dynamically generated divs

I have a div that generates multiple elements inside it:
<div class="lists">
<?php for($i=0;$i<6;$i++) { ?>
<div class="list history[[$i]]" id="history[[$i]]">
<div class="info">
<div class="picture monophoto">
<div class="text">BO</div>
<div class="img" style="background-image: url();"></div>
</div>
<div class="right">
<div class="lineone">John Smith</div>
<div class="linetwo">Daily Essentials</div>
</div>
</div>
<div class="boxes">
<div class="left">
<div class="box box1"></div>
</div>
<div class="right">
<div class="box box2"></div>
<div class="box box3"></div>
</div>
</div>
<a class="cbutton whiteonblack">VIEW LIST<!--SEE <span class="owner">JOHN'S</span>--></a>
</div>
<?php } ?>
</div>
I am trying to wrap the following div with an anchor tag so it links:
<div class="boxes"> </div>
Using jQuery I am trying to wrap this using jQuery that is part of a loop:
for(var i = 0; i < listLength; i++){
for(var y = 0; y < result.history[i].length; y++){
var history = document.getElementById('history' + i);
history.querySelector('.boxes').wrap('');
}
}
This is not resulting in an anchor tag showing up at all on the DOM. What am I doing wrong and how do I fix it?
Edit: I clarified which div
Edit 2: To clarify, each of the links are actually going to be dynamically generated. I am just using google.com as an example. So effecting all of a specific class wont work.
querySelector returns a NodeList object, wrap() is a jquery function, they won't work together, try this :
for(var i = 0; i < listLength; i++){
for(var y = 0; y < result.history[i].length; y++){
$('#history' + i).find('.boxes').first().wrap('');
}
}
You can do this in a single line by selecting the .list .boxes elements:
$('.lists .boxes').wrap('')
Example fiddle
Note that this will only work if you are using HTML5, otherwise it would be invalid to have a block level element (a div) inside an inline element (the a).

Categories

Resources