Conditionally rendering HTML elements with querySelector based on boolean value - javascript

I'm working on a Chrome extension so my approach is different to how I'd usually go about this.
I have the below HTML, which includes elements that may or may not be displayed depending on a boolean value in the javascript file:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="https://unpkg.com/mvp.css">
<link rel="stylesheet" href="popup.css">
</head>
<body class="container">
<header>
<h1 style="width: 400px">Title</h1>
<p style="font-size: 1rem;">Messages to non paying users</p>
<button class="join-btn">Join now!</button>
<a style="cursor: pointer; margin-top: 4px;">Message for paying users</a>
</header>
<script src="ExtPay.js"></script>
<script defer src="popup.js"></script>
</body>
</html>
The JS file is like so:
const extpay = ExtPay('my-ext-ID');
document
.querySelector('button')
.addEventListener('click', extpay.openPaymentPage);
document.querySelector('a').addEventListener('click', extpay.openPaymentPage);
extpay
.getUser()
.then((user) => {
if (user.paid) {
document.querySelector('p').innerHTML = 'Message to paying users';
document.querySelector('button').remove();
} else {
document.querySelector('a').remove();
}
})
.catch((err) => {
document.querySelector('p').innerHTML =
"Error fetching data :( Check that your ExtensionPay id is correct and you're connected to the internet";
});
So what this does is that if the user is a paying customer, then the contents of the <p> changes and the "Join now" button is removed, and if they are not a paying customer, the <a> is removed.
The problem I have with this approach is that for a short amount of time (<1sec) - the the HTML renders in its entirity (including both elements for paying & non-paying users) before the JS kicks in and updates accordingly. How can I update this so that this doesn't happen? I have tried adding defer to the script calls but to no avail.

You can try another approach, You can create empty div with id and then based on the conditions you can create those p and button elements and append it to that div. Like for example:
<header>
<h1 style="width: 400px">Title</h1>
<div id="header"></div>
<a style="cursor: pointer; margin-top: 4px;">Message for paying users</a>
</header>
<script>
const para = document.createElement("p");
const node = document.createTextNode("This is new.");
para.appendChild(node);
//append it to (document.getElementById('header'))
if (!user.paid) {
var a = document.createElement("button");
a.innerText = "Join now!";
//append it to (document.getElementById('header'))
}
</script>

Related

Dynamically loading json content within a HTML Script

I am writing a webpage using HTML and javascript. I have written a script (as seen below) that loads records from a json file. My script is meant to load data from the json file and display like a bootstrap alert. When I first ran it, the script worked, but strangely subsequent tests did not work. Does anyone have any ideas to fix this?
index.html:
<!DOCTYPE html>
<html>
<head>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<link type="text/css" href="css/style.css" rel="stylesheet">
<!-- Script in Question -->
<script type="text/javascript">
// This is a way to load data from a JSON file and load it into places in the html document. Based on: https://howtocreateapps.com/fetch-and-display-json-html-javascript/
fetch('alerts.json')
.then(function(response){
return response.json();
})
.then(function (data){
appendData(data);
})
.catch(function (err) {
console.log(err);
});
function appendData(data) {
var container = document.getElementById("alerts");
for (let i = 0; i < data.length; i++) {
var div = document.createElement("div");
div.className = "alert alert-primary";
div.setAttribute("role", "alert")
div.innerHTML = data[i].content;
container.appendChild(div)
}
}
</script>
<title>Guitars</title>
</head>
<body>
<div id="alerts" style="text-align: center;">
<!-- JSON data appears here -->
</div>
<div style="text-align: center;" id="main">
<!-- Other stuff here -->
</div>
<div style="text-align: center;">
<!-- Other stuff here -->
</div>
</body>
</html>
alerts.json:
[
{"content":"Welcome back, test1!"},
{"content":"Welcome back, test2!"},
{"content":"Welcome back, test3!"}
]
The code reads the records from alerts.json and inserts them into a div with an id "alerts" - as seen in the <script> tag. Any help would be greatly appreciated!
OP here. Thanks to user #David, it was suggested to clear out all errors found in the webpage debugging console. Upon clearing these up, the function then worked as intended!

Is the problem the onclick method or the represenation of the html element as a object

I'm new to javascript and this has been driving me nuts for the last hour
Here's the html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Number Guessing Game</title>
<link rel="stylesheet" href="styles/main.css">
</head>
<body>
<h1>Number Guessing Game</h1>
<p>Greetings hominid. I've selected a number between 1 and 100. See if you can guess it in 10 turns or fewer. I'll tell you if your guess was too high or too low.</p>
<label for="guess">Enter your guess:</label>
<input id="guess">
<button id ="submit">Submit</button>
<p id="response"></p>
<p id="guess-count"></p>
<p id="previous-guesses"></p>
<script src = scripts/game.js ></script>
</body>
</html>
And here's the javascript
const submitButton= document.getElementById('submit')
alert('hi')
submitButton.onClick = function submitGuess() {
alert('button is live')
}
For some reason the submitGuess function is not being executed at all (at least I'm not seeing the alert). I had a lot more javascript but I reduced it to find out why it wasn't working.
Any help is much appreciated
As pointed out in the comments, you can add the event handler in the JavaScript via EventTarget.addEventListener, rather than the inline HTML attribute. For example:
document.querySelector('#submit').addEventListener('click', event => {
console.log(`${event.target.id} was clicked`)
});
<h1>Number Guessing Game</h1>
<p>Greetings hominid. I've selected a number between 1 and 100. See if you can guess it in 10 turns or fewer. I'll tell you if your guess was too high or too low.</p>
<label for="guess">Enter your guess:</label>
<input id="guess">
<button id="submit">Submit</button>
<p id="response"></p>
<p id="guess-count"></p>
<p id="previous-guesses"></p>
const submitButton = document.getElementById('submit')
this line get the value before the DOM fully loaded the solution is to define the const after the page load like this
window.onload = function(){
const submitButton = document.getElementById('submit')
alert('hi')
if(submitButton){
submitButton.addEventListener('click', function() {
alert("Clicked!");
});
}else{
alert("Something Wrong")
}
}

JavaScript ground work for creating a bubble game

I need help with Javascript fundamentals the issue I am having is with my start button when it clicks on it supposed to create a prompt that asks the user for the first name and have it stored within that variable you created. I have the doc ready function working okay however the button is not working properly.
Here is my code and thank you for helping me
<!-- Name: <Put name here> Date: <Put date here> Class: CSCI2447, Javascript Fundamentals Project X \-->
<!DOCTYPE html>
<html>
<head>
<title>POP-The- Bubble (CSCI2447)</title>
<!-- CSS styles: This is for me to worry about; not you. -->
<link href="css/game.css" rel="stylesheet" />
<link href="[https://fonts.googleapis.com/css2?family=Sunshiney&display=swap](https://fonts.googleapis.com/css2?family=Sunshiney&display=swap)" rel="stylesheet">
<script src = "jquery-3.5.1.min.js"> </script>
<script> $( document ).ready(function() { var first Name = prompt("Enter First Name of Gamer:"); </script>
</head>
<body>
<div id="content">
<h1>Pop-The-Bubble</h1>
<p>After clicking "start", you will have 30 seconds to click
on as many bubbles as you can. The bubbles will appear quickley so be ready!
</p>
<div id="controls">
<span id="score">0 pts</span>
<button type="button" id="start\_button">Start!</button>
</div>
<div id="gamespace">
<img class="gameimage" src="img/bubblefun2.png" height = "120" width = "120"
</div>
</body>
</html>
Your function should close with the closing curly braces } and bracket ) => })
$( document ).ready(function() { var firstName = prompt("Enter First Name of Gamer:") });
Also you have a space between first and Name, this will throw an error in javascript Unexpected identifier. Remove the space so it is one string as the variable name firstName

Javascript - looping through data with each click

I'm fairly new to Javascript I have been playing with some data fetching for the past few days. I created this very simple program (if you can even call it that), where if you click a button, it will generate a div with a random user (using jsonplaceholder API). My issue is, that whenever the button is clicked, it gives me all 10 users at once. I'd like it to give me one user with each click instead. As I said, I am fairly new to JS so I'm not sure how to aproach this (I guess some sort of a loop would be involved?). Any sort of advice, tips or anything would be welcomed ! Thank you !
Here is my code (Using Bootstrap 4 for styling and Axios for data fetching):
const mainButton = document.getElementById('mainButton');
const targetDiv = document.getElementById("targetDiv");
mainButton.addEventListener('click', () => {
axios
.get("https://jsonplaceholder.typicode.com/users")
.then(function(response) {
let ourRequest = response;
renderData(ourRequest.data);
})
.catch(function(error) {
console.log(error);
});
function renderData(data) {
var stringHTML = "";
for (i = 0; i < data.length; i++) {
stringHTML += `
<div class="col-md-4">
<div class="card">
<div class="card-header">
User ID: #${data[i].id}
</div>
<div class="card-body">
<h4 class="card-title">${data[i].name}</h4>
<p class="card-text">Email - <em>${data[i].email}</em></p>
<p class="card-text">Phone - <em>${data[i].phone}</em></p>
<p class="card-text">Address - <em>${data[i].address.street}, ${data[i].address.city}, ${data[i].address.zipcode}</em></p>
</div>
</div>
</div>
`;
}
targetDiv.insertAdjacentHTML("beforeend", stringHTML);
}
});
<!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">
<link rel="stylesheet" href="main.css">
<title>JSON Users</title>
</head>
<body>
<div class="container">
<div class="text-center my-5">
<h1 class="display-4">Random JSON Users</h1>
<p>This is a random user generator, click the below button to get a
random person!</p>
<button id="mainButton" class="btn btn-primary">Get User!</button>
</div>
<!-- Users -->
<div id="targetDiv" class="row">
</div>
</div>
<!-- JavaScript -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="main.js"></script>
</body>
</html>
If I get it right that your GET method is asking for users, so response contains more that one user. This response you send to renderData method and there you generate your div for each user from response. I supouse to change your GET method to get only one user or send only one user to renderData method like ourRequest.data[0] from your current solution.

How to display different HTML elements in if statement

Hello, I am new to HTML and JS therefore would like to ask for some help.
Here I want to display two different HTML elements according if statement is true or false. However, it does not work.
Could I get some help? (:
<!DOCTYPE html>
<html>
<body>
<script>
if (!user) {
<h1> there is no user </h1>
} </script>
if (user) {
<button type="button">Click Me!</button>
} </script>
</body>
</html>
Here is a native Javascript alternative
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="content"></div>
<script>
var el = document.getElementById('content');
var content;
if (!user) {
content = '<h1>there is no user</h1>';
}
if (user) {
content = '<button type="button">Click Me!</button>';
}
el.insertAdjacentHTML('afterbegin', content);
</script>
</body>
</html>
This won't work as is unless the user variable is defined, though, but I'm assuming you already have it available at runtime.
If you have more html in this div you can use a different insert position, see the documentation about it here: https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML
Using jQuery you would do something like this
html
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
</body>
</html>
JS
if(!user){
$('body').append('<h1>There is no user</h1>')
} else if(user) {
$('body').append('<button>Login</button>')
}
See js fiddle here.
Also, note that if you want to use jquery include the script in the head
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
Unfortunately you can't add HTML directly in a block of javascript. What you can do instead though is use jQuery to append a block of HTML.
To do this, you would load jQuery by adding this line to your head tag
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"></script>
And then replace your inline javascript with the following:
<script>
if (!user) {
$(document.body).append( "<h1> there is no user </h1>" );
}
if (user) {
$(document.body).append( "<button type='button'>Click Me!</button>" );
} </script>

Categories

Resources