HTML
<html lang="en">
<head>
<title>Document</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="firstapp.js"></script>
</head>
<body>
<div id="buttons">
<h1>Hello</h1>
<h2>0</h2>
<button class="btn btn-primary" type="submit">Hello</button>
<button class="button2">count </button>
</div>
</body>
</html>
Javascript
let x = 0
function counter() {
x++;
document.querySelector('h2').innerHTML = x;
if (x % 10 === 0) {
alert(`counter is now ${x}`);
}
}
document.addEventListener("DOMContentLoaded", function() {
document.querySelector('.button2').onclick = counter; //This statement is for counter function
document.querySelector('.btn btn-primary').onclick = function() { //This is Hello Function
let heading1 = document.querySelector('h1');
if (heading1.innerHTML === "Hello!!") {
heading1.innerHTML = "Goodbye!!";
//document.querySelector('.btn btn-outline-secondary').innerHTML = 'goodbye';
} else {
heading1.innerHTML = "Hello!!";
//document.querySelector('.btn btn-outline-secondary').innerHTML = 'Hello!!';
}
};
})
When I Document.queryselector with a local css file it works just fine but as soon as I link a bootstrap class the Java scropt doesn't recognize any bootstrap class and gives out an error " TypeError: Cannot set property 'onclick' of null
at HTMLDocument. "
In JavaScript, elements are selected with CSS selectors, not HTML syntax.
Change
document.querySelector('.btn btn-primary')
to
document.querySelector('.btn.btn-primary')
to denote an element with two class names. Do similarly with the rest by changing spaces to dots.
in primay button add new class for ex 'pbtn' and replace this
document.querySelector('.btn btn-primary')
with this
document.querySelector('.btn.btn-primary')
Related
I'm trying to create an Etch-a-Sketch project, I was going well (I think) until start to create a function that apply another size to my grid element, how can I do my function setSize() reads my function showSize() value?
Explanation:
My function showSize() shows the value of a range input element, and I need to apply this value to my function populateBoard(), so I have created setSize() function to do that, Am I right creating this intermediary function to do that?
These are my codes:
function populateBoard(size){
let board = document.querySelector(".board");
board.style.gridTemplateColumns = `repeat(${size}, 1fr)`;
board.style.gridTemplateRows = `repeat(${size}, 1fr)`;
for (let i = 0; i < 256; i++) {
let square = document.createElement("div");
square.style.backgroundColor = "green";
board.insertAdjacentElement("beforeend", square);
}
}
populateBoard(16);
function showSize(value) {
let boardSize = document.querySelector(".show-size").innerHTML = value;
}
function setSize(boardSize) {
let setSize = document.querySelector(".set");
setSize.addEventListener("click", () => {
populateBoard(boardSize);
});
}
<!DOCTYPE html>
<html>
<head>
<title>
Etch-a-Sketch
</title>
<meta charset="utf-8">
<link rel="stylesheet" href="styles.css">
<script src="script.js" defer></script>
</head>
<body>
<div class="container">
<div class="board">
</div>
<div class="settings">
<button class="clear">Clear</button>
<input type="range" min="8" value="16" max="128" step="8" oninput="showSize(this.value)">
<span class="show-size">16</span>
<button class="set">Set</button>
</div>
</div>
</body>
</html>
The problem is that you are defining the boardSize variable in the showSize function so that variable is only available in the scope of that function. Please read the following:
https://www.w3schools.com/js/js_scope.asp
I suggest you do the following.
document.querySelector(".set").addEventListener("click", () => {
let boardSize = document.querySelector(".show-size").innerHTML;
populateBoard(boardSize);
});
function setSize(value) {
document.querySelector(".show-size").innerHTML = value;
}
Some errors you have is setting the event listener in a function.
I would just have a function to set the board size as seen above and then the event listener to populate the board onclick of the set size button.
I am trying to make an event when two numbers randomly generated are equal.So I need to store values in a variable in javascript and see if they are equal.
if (target_number == you_score){
console.log(1)
}
I have put console.log in there to test if the statement is executed
const button = document.querySelector('target_number')
function getRandomNumber() {
return Math.floor(Math.random() * 10)
}
function getRandomNumber2() {
return Math.floor(Math.random() * 10)
}
function getRandomNumber3() {
return Math.floor(Math.random() * 10)
}
document.getElementById("target_number").addEventListener("click", displayGuess);
function displayGuess(){
document.getElementById("target_number").innerHTML = getRandomNumber();
}
document.getElementById("target_number").style.cursor = "pointer";
document.getElementById("computer_score").addEventListener("click", displayGuess2);
function displayGuess2(){
document.getElementById("computer_score").innerHTML = getRandomNumber2()
}
document.getElementById("computer_score").style.cursor = "pointer";
document.getElementById("you_score").addEventListener("click", displayGuess3);
function displayGuess3(){
document.getElementById("you_score").innerHTML = getRandomNumber3()
}
document.getElementById("you_score").style.cursor = "pointer";
var computerScore = document.getElementById("computer_score")
var youScore = document.getElementById("you_score")
var targetNumber = document.getElementById("target_number")
Here is my HTML. I would like to make a if else statement in script that checks if the value of target_number and computer_score are equal
<!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>Number Guesser</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div>
<h1>Number Guesser</h1>
</div>
<div>
<h2>Round
<span class="round_number">1</span>
</h2>
</div>
<h3>Target Number: <span id="target_number">Blank</span></h3>
</body>
<div class="container">
<div class="computer">Computer
<div>Score <span id="computer_score">0</span></div>
</div>
<div class="you">You
<div>Score <span id="you_score">0</span></div>
</div>
</div>
<h1 id="new">New</h1>
<script src="script.js"></script>
</html>
Based on what it looks like you mean, I have simplified your code using event delegation, some css and a single function to generate a random number lower than 10.
const someNumberLT10 = () => Math.floor(Math.random() * 10);
document.addEventListener(`click`, handle);
function handle(evt) {
if (evt.target.id === "play") {
// ^ button#play was clicked
const youNr = someNumberLT10();
const computerNr = someNumberLT10();
// two random numbers < 10 are generated and stored into variables
document.querySelector(`#you_score`).textContent = youNr;
document.querySelector(`#computer_score`).textContent = computerNr;
// ^ numbers are displayed
document.querySelector(`#equal`).textContent = `Equal? ${
youNr === computerNr ? `Yes! 😊` : `Nope ... 😔`}`;
// ^ score (equal or not) is displayed
const round = document.querySelector(`[data-round]`);
round.dataset.round = +round.dataset.round + 1;
// ^ round index is set
}
}
[data-round]:after {
content:' 'attr(data-round);
}
<h2 data-round="1">Round</h2>
<!-- data-round is a so called data attribute. It can be used as a variable
in js (dataset). Here, js is used to set the value, and css is used
to display the value ([data-round]:after) -->
<h3>Target Number: <button id="play">Create</button></h3>
<div class="container">
<div>Computer score <span id="computer_score">0</span></div>
<div>Your score <span id="you_score">0</span></div>
<div id="equal"></div>
</div>
Please note that I am not using classes. I haven't found an answer for this SPECIFIC question.
Using javascript, how can I program a button to change the stylesheet each time the button is clicked?
I've tried different if, else if and else, but when I try them, it breaks the code (ie, it will change the color to blue if red, but not back again).
It works with 2 buttons, but getting it to change each time a single button is clicked seems to be eluding me. I got feed up and programmed a second button to change it back.
This works for 2 buttons:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>"Your Title Here"</title>
<link id="um" rel="stylesheet" href="stylesheet1.css">
<style>
</style>
</head>
<body>
<p>booga</p>
<button id="x" onclick="myFunction()">blue</button>
<button id="x1" onclick="myFunction1()">red</button>
<script>
function myFunction() {
if (document.getElementById("um").href = "stylesheet1.css"){
document.getElementById("um").href = "stylesheet2.css"}
}
function myFunction1() {
if (document.getElementById("um").href = "stylesheet2.css"){
document.getElementById("um").href = "stylesheet1.css"}
}
</script>
</body>
I would like to be able to get rid of the second button and second function and have it all with one button.
EDIT...
I tried this, and it failed.
function myFunction() {
if (document.getElementById("um").href == "stylesheet1.css")
{document.getElementById("um").href = "stylesheet2.css"};
else {document.getElementById("um").href = "stylesheet1.css"}
}
Make sure you're using == instead of = for your comparisons!
if (document.getElementById("um").href == "stylesheet1.css")
etc
Try this:
<button id="x" onclick="myFunction()">Change</button>
<script>
function myFunction() {
var link = document.getElementById("um");
var segments = link.href.split('/');
var currentStyle = segments[segments.length - 1];
var style = (currentStyle == 'stylesheet1.css') ? 'stylesheet2'
: 'stylesheet1';
document.getElementById("um").href = style + ".css"
}
</script>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>"Your Title Here"</title>
<link id="um" rel="stylesheet" href="stylesheet1.css">
</head>
<body>
<p>booga</p>
<button onclick="myFunction('um','stylesheet1.css', 'stylesheet2.css')">swap</button>
<script>
function myFunction(id,a,b) {
var el = document.getElementById(id);
var hrefStr;
if(~el.href.indexOf(a)) {
hrefStr = el.href.replace(a, b);
el.href = hrefStr;
} else {
hrefStr = el.href.replace(b, a);
el.href = hrefStr;
}
}
</script>
</body>
</html>
So I have a website with a Header.html. In the header are three buttons. I've copied the Header.html into all of my other pages with jquery's load. Now what I would like to do is change the colour of one of the buttons depending on the page it's on. But when I use document.GetElementById in javascript it can't find the div of the button I've copied from the Header.html
Here's the Header.html
<div id="Header_Wrapper">
<div id="Header_PageLinksWrapper">
<div class="Header_PageLink">
<a class="Header_PageLinkText" id="PageLink_Games" href="..\Pages\Games.html">Games</a>
</div>
<div class="Header_PageLink">
<a class="Header_PageLinkText" id="PageLink_AboutMe" href="..\Pages\AboutMe.html">About Me</a>
</div>
<div class="Header_PageLink">
<a class="Header_PageLinkText" id="PageLink_CV" href="..\Pages\CV.html">CV</a>
</div>
</div>
</div>
The javascript file:
$(document).ready(
function ()
{
$("#Header").load("..\\Templates\\Header.html");
var filePath = window.location.pathname;
SetPageLinkColours(filePath);
}
);
function SetPageLinkColours(aPath)
{
var firstIndex = aPath.lastIndexOf("/");
var lastIndex = aPath.indexOf(".html");
var id = "PageLink_" + aPath.slice(firstIndex + 1, lastIndex);
var divElement = document.getElementById(id);
if (divElement == null)
{
console.log("Could not find element " + id);
}
divElement.style.color = 0xffffff;
}
One of the pages (eg. Games.html)
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Adabelle Combrink - Games</title>
<link rel="stylesheet" type="text/css" href="..\Templates\Header.css"/>
<link rel="stylesheet" type="text/css" href="..\Templates\Page.css"/>
<link rel="stylesheet" type="text/css" href="..\Pages\Games.css"/>
<script type="text/javascript" src="..\Scripts\jQuery.js"></script>
<script type="text/javascript" src="..\Scripts\Defaults.js"></script>
</head>
<body>
<header>
<div id="Header"></div>
</header>
</body>
</html>
What this gives me in the console is Could not find element PageLink_Games. I don't get that error if I use something that is in Games.html like Header.
Is there any other way of doing the same thing. I know you can include files into eachother with php but I haven't gotten that right and don't seem to be able to run .php files in Visual Studio.
jQuery.load has a success callback. Use it to assure your code is only executed after the loading is complete.
$(document).ready(
function ()
{
$("#Header").load("..\\Templates\\Header.html", null, function() {
var filePath = window.location.pathname;
SetPageLinkColours(filePath);
});
}
);
Also your SetPageLinkColours function can be improved with jQuery:
function SetPageLinkColours(aPath)
{
var firstIndex = aPath.lastIndexOf("/");
var lastIndex = aPath.indexOf(".html");
var id = "PageLink_" + aPath.slice(firstIndex + 1, lastIndex);
var divElement = $("#"+id);
if (!divElement.length)
{
console.log("Could not find element " + id);
}
else
{
divElement.css('color','white');
}
}
load function makes async request , so your code tries to find element before it rely appears. U need to use load function callback http://api.jquery.com/load/
$(document).ready(
function ()
{
$("#Header").load("..\\Templates\\Header.html", function () {
var filePath = window.location.pathname;
SetPageLinkColours(filePath);
});
}
);
I got this HTML code:
<head>
<script type="application/javascript" src="javascript.js">
<link id="pagestyle" href="default.css" rel="stylesheet" type="text/css" />
</head>
<body>
<button id="stylesheet1" > Default Style Sheet </button>
<button id="stylesheet2" > Dark Style Sheet </button>
</body>
And in javascript.js I got this:
function swapStyleSheet(sheet) {
document.getElementById("pagestyle").setAttribute("href", sheet);
}
function initate() {
var style1 = document.getElementById("stylesheet1");
var style2 = document.getElementById("stylesheet2");
style1.onclick = swapStyleSheet("default".css);
style2.onclick = swapStyleSheet("dark".css);
}
window.onload = initate;
I want to the style sheets to change while pressing this buttons. I can't figure out why it is not working.
One guess would be the missing .css property, another would be the fact that onclick is not a function, but a result from invoking one:
Make all of .css a string and assign functions to onclick:
style1.onclick = function () { swapStyleSheet("default.css") };
style2.onclick = function () { swapStyleSheet("dark.css"); };
Transform "default".css into "default.css".
Do the same for dark.css.
Then onclick takes a function as a value.
style1.onclick = function () { swapStyleSheet("default.css") };
style2.onclick = function () { swapStyleSheet("dark.css") };
$('button').click(function() {
let mainSheet = $('#pageStyle').attr('href');
if(mainSheet == "default.css")
$('#pageStyle').attr('href','dark.css');
else
$('#pageStyle').attr('href','default.css');
});
Hello it Won't work until you add onclick="" property in html
So the final version will look like this:
html
<head>
<script type="application/javascript" src="javascript.js">
<link id="pagestyle" href="default.css" rel="stylesheet" type="text/css" />
</head>
<body>
<button id="stylesheet1" onclick="initate();"> Default Style Sheet </button>
<button id="stylesheet2" onclick="onclick="initate();"> Dark Style Sheet </button>
</body>
Javascript file
function swapStyleSheet(sheet) {
document.getElementById("pagestyle").setAttribute("href", sheet);
}
function initate() {
var style1 = document.getElementById("stylesheet1");
var style2 = document.getElementById("stylesheet2");
style1.onclick = swapStyleSheet("default.css");
style2.onclick = swapStyleSheet("dark.css");
}