Show one random icon on page load - javascript

How do I show one random icon on page load with js? Below is the HTML code I have:
<span>
<i class="fa fa-trash-o" id="icon-one"></i>
<i class="fa fa-frown-o" id="icon-two"></i>
<i class="fa fa-thumbs-o-down" id="icon-three"></i>
</span>
I need to show only one of the three icons.

My HTML would be
<span id = "mySpan"></span>
You can do this using javascript
var myRand = Math.floor(Math.random() * 3) + 1;
var randString = '';
if(myRand == 1)
randString = 'one';
else if(myRand == 2)
randString = 'two';
else if(myRand == 3)
randString = 'three';
var ele = document.createElement("div");
ele.setAttribute("id","icon-"+randString );
document.getElementById("mySpan").appendChild(ele);
Well , this assumes that your ids have the icon and not the classes

<span>
<i class="fa fa-trash-o" style="display: none;" id="icon-one"></i>
<i class="fa fa-frown-o" style="display: none;" id="icon-two"></i>
<i class="fa fa-thumbs-o-down" style="display: none;" id="icon-three"></i>
</span>
var icons = [ 'icon-one', 'icon-two', 'icon-three' ],
icon = icons[Math.floor(Math.random()*icons.length)];
$( '#' + icon ).show();
This should work if you are using jquery.

use this function to get a random no in range(min, max)
function getRandomArbitary (min, max) {
return Math.random() * (max - min) + min;
}
and use appropriately to show the tag hide other wise
such as
js
var r = function getRandomArbitary (1, 3);
var eleCategory = document.getElementById("main_div");
var eleChild = eleCategory.childNodes;
for( i = 0 , i<eleChild.length; i++ ){
if(i==r){
eleChild[ i ].style.display='block';
}
else
{
eleChild[ i ].style.display='none';
}
}
html
<span id="main_div">
<i class="fa fa-trash-o" id="icon-one"></i>
<i class="fa fa-frown-o" id="icon-two"></i>
<i class="fa fa-thumbs-o-down" id="icon-three"></i>
</span>

you can use java script here. So if there are only three icons one , two and three.
use random function to generate a number between one two and three
var x= Math.floor((Math.random()*3)+1);
if (x==1)
{
//fetch the div id = "icon-one" and display
}
else if (x==2)
{
//fetch the div id = "icon-two" and display
}
else
{
//fetch the div id = "icon-three" and display
}
Although this will work way better if you can rename your id's two icon1,icon2 and so on
it will just be this then :
var x= Math.floor((Math.random()*3)+1);
var icon = "icon";
var id = icon.concat(x);

Simple work woth using jQuery.
Working jsFiddle

Related

show the number of likes when click the like button

I try this concept but it not success, When I click the like button
then count of likes will be increase by 1 again I press that button
then it decrease by 1. For example, Now the count is 5 I click the
like button then the count is 6, again I press now the count is 5
(like Facebook).
JSP
<button class="like_btn" onclick="like()">
<span id="icon"><i class="far fa-thumbs-up"></i></span> <span
id="count">0</span>Like
</button>
JavaScript
function like(){
const likeBtn = document.querySelector(".like_btn");
let likeIcon= document.querySelector("#icon");
let count = document.querySelector("#count");
let clicked = false;
likeBtn.addEventListener("click", () => {
if (!clicked) {
clicked = true;
likeIcon.innerHTML = `<i class="fas fa-thumbs-up"></i>`;
count.textContent++;
}else{
clicked = false;
likeIcon.innerHTML = `<i class="far fa-thumbs-up"></i>`;
count.textContent--;
}
});
}

onclick with two function calls takes two clicks to run both functions js

This is probably going to be marked as a duplicate because there are so many SO questions about this already, but I'm just unable to apply those questions answers onto my code.
I am using Razor, html, css, and javascript in my Blob storage page code.
On the left side in the image below there are three containers. When clicking on one of them they are to open up and show all their children (blobs). The first time I click one of the containers only one of the function calls run (listContainerBlobs()) and it is not the one opening the container up (showHide()).
Below is the html p-tag calling the functions onclick.
<p class="blob-container" onclick="showHide('#containerId', '#arrowId');listContainerBlobs('#jsonBlob', '#container.Name');"><i class="fa fa-caret-right" id="#arrowId"></i> #container.Name</p>
The full div with C# and razor:
<aside class="aside">
<div class="aside-header">
<i class="fa fa-plus add-container-button aside-header-icons" onclick="addContainer()"></i><i class="fa fa-search search-button aside-header-icons"></i>
<input id="searchBox" type="text" onkeyup="search()" name="search" placeholder="Search blobs..." />
</div>
<div class="aside-containers">
#foreach (var container in containers)
{
caretArrowNumber++;
string arrowId = "arrowId-" + caretArrowNumber;
containerNumber++;
string containerId = "containerId-" + containerNumber;
var blobs = await Model.ListContainerBlobs(container.Name);
//var jsonBlob = Json.Serialize(blobs);
List<object> blobObject = new List<object>();
blobObject.Add(new
{
blobCount = blobs.Count,
blobs = blobs.Select(x => new
{
Name = x.Name,
Container = container.Name,
Blobtype = x.BlobType,
Uri = x.Uri
})
});
var jsonBlob = JsonConvert.SerializeObject(blobObject);
<div class="arrow-blob-container">
<p class="blob-container" onclick="showHide('#containerId', '#arrowId');listContainerBlobs('#jsonBlob', '#container.Name');"><i class="fa fa-caret-right" id="#arrowId"></i> #container.Name</p>
</div>
<div class="showBlob" id="#containerId">
<div class="ml-4">
#foreach (var blob in blobs)
{
blobNumber++;
string blobId = "blobId-" + blobNumber;
<div>
<input class="blobs" id="#blobId" type="button" value="#blob.Name" onclick="downloadBlob('#blobId', '#blob.Name', '#blob.Container.Name')" />
</div>
}
</div>
</div>
}
</div>
</aside>
The following code is the two functions being called on onclick:
<script>
function listContainerBlobs(json, container) {
console.log("beginning");
console.log(json);
var arr = JSON.parse(json);
console.log(arr);
var blobs = document.getElementById('container-blob-display').innerHTML = "<h4>" + container + "</h4>";
var otherDiv = document.getElementById('section-1');
var thisDiv = document.getElementById('section-2');
otherDiv.style.display = 'none';
thisDiv.style.display = 'inline';
var blobNumber = 0;
for (i = 0; i < arr.length; i++){
blobNumber++;
var blobId = "blobId" + blobNumber;
blobs += "<p class='search-result' id='" + blobId + "' onclick='downloadBlob('" + blobId + "', '" + arr[i].Name + "', '" + container + "')'>" + arr[i].Name + "</p>";
}
console.log(blobs);
}
function showHide(containerId, arrowId) {
var c = document.getElementById(containerId);
var a = document.getElementById(arrowId);
if (c.style.display === "none") {
c.style.display = "inline";
a.className = "fa fa-caret-down";
} else {
c.style.display = "none";
a.className = "fa fa-caret-right";
}
}
</script>
I have tried
commenting out the ListContainerBlobs()-function
commenting out all the css
changed from style.display = "block" to "inline" (seen in the example code)
moved the whole script section to the top of the html
commented out almost all code in the html except the most necessary
But showHide() still wouldn't run on the first click.
So currently, on the first click the listContainerBlobs() run and on the second click the showHide() runs, but I would prefer if both of them ran on the first onclick.
I appreciate all the help I can get! Thanks in advance!
P.S I'd love to do a jsfiddle but it doesn't seem to understand C# and List<> (thinking <> is a tag)
Edit from Mr. Smiths solution
It still takes two clicks for me to run both functions with this solution from Mr. Smith:
HTML:
<div class="arrow-blob-container">
<p class="blob-container aside-content" id="#newContId" data-containerId="#containerId" data-arrowId="#arrowId" data-jsonBlob="#jsonBlob" data-containerName="#container.Name"><i class="fa fa-caret-right" id="#arrowId"></i> #container.Name</p>
</div>
Js:
document.querySelectorAll('.aside-content').forEach(element => {
element.addEventListener('click', function (e) {
let ds = this.dataset;
showHide(ds.containerid, ds.arrowid);
listContainerBlobs(ds.jsonblob, ds.containername);
})
});
This works all the way with the right ids and other values, but like I said, I still need to click two timesto get both functions to be called. First click runs listContainerBlobs(), second click showHide().
Any ideas of why that might be?
You can create an event listener which calls your functions:
<div class="arrow-blob-container">
<p class="blob-container" data-container-id="#containerId" data-arrow-id="#arrowId" data-json-blob="#jsonBlob" data-container-name="#container.Name" ><i class="fa fa-caret-right" id="#arrowId"></i> #container.Name</p>
</div>
Script:
<script>
document.querySelectorAll('.blob-container').forEach(element => {
element.addEventListener('click', function(e) {
let dataset = e.currentTarget.dataset;
showHide(dataset.containerId, dataset.arrowId);
listContainerBlobs(dataset.jsonBlob, dataset.containerName);
});
});
</script>
Check this snippet:
document.querySelectorAll('.blob-container').forEach(element => {
element.addEventListener('click', function(e) {
let dataset = e.currentTarget.dataset;
console.log("containerId: " + dataset.containerId);
console.log("arrowId: " + dataset.arrowId);
console.log("jsonBlob: " + dataset.jsonBlob);
console.log("containerName: " + dataset.containerName);
});
});
<div class="arrow-blob-container">
<button class="blob-container" data-container-id="container1" data-arrow-id="arrow1" data-json-blob="{...}" data-container-name="Button1">Display dataset</button>
<button class="blob-container" data-container-id="container2" data-arrow-id="arrow2" data-json-blob="{...}" data-container-name="Button2">Display dataset</button>
<button class="blob-container" data-container-id="container3" data-arrow-id="arrow3" data-json-blob="{...}" data-container-name="Button3">Display dataset</button>
<button class="blob-container" data-container-id="container4" data-arrow-id="arrow4" data-json-blob="{...}" data-container-name="Button4">Display dataset</button>
</div>
This also works without querySelector which might be clearer:
function onButtonClick(e) {
let dataset = e.dataset;
console.log("containerId: " + dataset.containerId);
console.log("arrowId: " + dataset.arrowId);
console.log("jsonBlob: " + dataset.jsonBlob);
console.log("containerName: " + dataset.containerName);
}
<div class="arrow-blob-container">
<button class="blob-container" onClick="onButtonClick(this)" data-container-id="container1" data-arrow-id="arrow1" data-json-blob="{...}" data-container-name="Button1">Display dataset</button>
<button class="blob-container" onClick="onButtonClick(this)" data-container-id="container2" data-arrow-id="arrow2" data-json-blob="{...}" data-container-name="Button2">Display dataset</button>
<button class="blob-container" onClick="onButtonClick(this)" data-container-id="container3" data-arrow-id="arrow3" data-json-blob="{...}" data-container-name="Button3">Display dataset</button>
<button class="blob-container" onClick="onButtonClick(this)" data-container-id="container4" data-arrow-id="arrow4" data-json-blob="{...}" data-container-name="Button4">Display dataset</button>
</div>

Active nav bar doesn't change the first time

I am trying to change navigation a tag color when the user clicks on the <a> tag. The JS is working fine, except the first time the user clicks on the <a> tag; only in the second time the a tag color changes.
JavaScript:
function toggleNav(pageId){
activeColor();
var href = 'html/' + pageId + '.html';
window.onload = document.getElementById('main').innerHTML =
loadPage(href);
}
function activeColor(){
var header = document.getElementById("allNav");
var btns = header.getElementsByClassName("notActive");
for (var i = 0; i < btns.length; i++) {
var button1 = btns[i];
button1.addEventListener("click" ,
function() {
var current = document.getElementsByClassName(" active");
console.log(current.length);
for (var i = 0; i < current.length + 1; i++) {
current[0].className = current[0].className.replace("
active", "");
}
var myString = this.id;
var stringLength = myString.length;
var lastChar = myString.charAt(stringLength - 1);
if(lastChar == "2"){
var add = document.getElementById(this.id);
var id2Nmae = add.id.slice(0, -1);
var add2 = document.getElementById(id2Nmae);
add.className += " active";
add2.className += " active";
}
else{
var add = document.getElementById(this.id);
var id2Nmae = add.id + "2";
var add2 = document.getElementById(id2Nmae);
add.className += " active";
add2.className += " active";
}
});
}
}
HTML :
<div id="allNav">
<div class="sidebar" id="mySidebar" style="display:block">
<button id="open" onclick="Toggle()">
<a ><i class="fas fa-bars"></i></a>
</button>
<i class="glyphicon glyphicon-screenshot"></i>
<i class="glyphicon glyphicon-exclamation-sign"></i>
<i class="fas fa-burn"></i>
<i class="fas fa-utensils"></i>
<i class="fa fa-line-chart"></i>
<i class="far fa-comments"></i>
<i class="fas fa-bell"></i>
</div>
I succeeded to solve the problem, It was an issue I made by the DOM path not correct.
In the first time the page loads, the default load was the "goals" id by the next JS code:
var href = 'html/goals.html';
window.onload = document.getElementById('main').innerHTML = loadPage(href);
In this why the "addEventListener" needed to load at the first time and only in the second time the function can run.
I changed the default function to:
toggleNav('goals')
I hope I helped if somebody will experience the same issue.
Thanks for the help.
I ran your script and in the console I got
Uncaught TypeError: Cannot read property 'id' of null
(in chrome dev tools) Have you checked the element view (next to console) to see how the javascript is interacting with the HTML?
from looking at the code, the number "2" is for ids that are selected, however, everything ends with the number 2 and it is never actually removed. Is that intentional?
The loop doesn't seem to like "this.id" as it loses the reference (error above).
have you put in alerts to see where the pointer is in the loop?

How can I add condition in string javascript?

My javascript code like this :
var res = `<td>
if(product.photo == photo.name)
<div class="box-check">
<span class="fa fa-check"></span>
</div>
</td>`;
I try like that. But seems it's wrong
How can I do it?
simplest (easiest) change I can think of is as follows:
var inner = product.photo == photo.name ? `<div class="box-check">
<span class="fa fa-check"></span>
</div>` : '';
var res = `<td>${inner}</td>`;
alternatively
var res = `<td>${product.photo == photo.name?'<div class="box-check"><span class="fa fa-check"></span></div>':''}</td>`;
but you can NOT (easily) make the <div><span etc multiline in this case
I didn't try hard enough - nested template literals FTW :p
var res = `<td>${product.photo == photo.name?`<div class="box-check">
<span class="fa fa-check"></span>
</div>`:''}</td>`;

Changing Variable Value on Click in Javascript

Okay, so I am using the dribbble API to GET my works from dribbble
I set up a few VAR's to help with the process;
var dribbble = 'crobertson97';
var limit = '10'; //items per page
var per_page = '&per_page='+limit+''; //url
var accessToken = '12345678910'; //client
var url = 'https://api.dribbble.com/v1/users/'+dribbble+'/shots/?access_token='+accessToken+'&callback=?'+per_page; //url
I want to add a view more button that if clicked will do three things;
the button <a id="readmore" class="btn btn-success white"> View More</a>
Change the text of the button from view more to view less
Change the var limit = 10 to 20
3.Be able to revert --> view less
Add an onclick function to the html:
<a id="readmore" class="btn btn-success white" onclick="buttonClick(this)"> View More</a>
And create the following function in the JS:
function buttonClick(but) {
if(limit==10) {
limit = 20;
but.innerHTML= "View less";
} else {
limit = 10;
but.innerHTML = "View more";
}
}
There's still the display of the content to manage, but you didn't give much information about what you want and how the data is given!
Pretty easy, using modern web API.
readmore.addEventListener('click', readmoreless);
var limit = 10;
function readmoreless(){
if(limit == 10){
readmore.innerHTML = "View Less";
limit = 20;
} else {
readmore.innerHTML = "View More";
limit = 10;
}
}
<a id="readmore" class="btn btn-success white">View More</a>

Categories

Resources