Resizing grids with JavaScript - javascript

I have been stuck on this problem for quite some time. I am just looking to get some hints or get pointed in the right direction, as I am trying my absolute hardest to work through this problem.
Introduction: I am working through The Odin Project - Etch-a-Sketch. In this problem I am to create a 16x16 grid, using JavaScript to create the divs that make up that grid. Then I create a button that has a prompt appear and the user input becomes the new size of the grid. For example, if the user input is "50" the grid goes from 16x16 to 50x50. All of these steps have been completed up until getting the user's input.
The problem: I have no idea how to take the value from my user input, and make it change my grid size.
Here is my code:
const btn = document.querySelector("button");
btn.addEventListener("click", function () {
var userInput = prompt(
"Please enter the amount of grids you want to be in our Etch-a-Sketch. It needs to be between 1 and 100."
);
console.log(userInput);
if (userInput > 0 && userInput < 101) {
console.log("We are going to make a grid of " + userInput + " divs");
} else {
console.log(
"You chose " +
userInput +
" and unfortunately that is too big. Please enter a value between 1 and 100."
);
}
for (i = 0; i < userInput * userInput; i++) {
let gridDiv = document.createElement("div");
gridDiv.className = "gridDiv";
document.getElementById("container").appendChild(gridDiv);
}
document.querySelectorAll(".gridDiv").forEach((v) => {
v.addEventListener("mouseover", (e) => {
e.target.style.background = "black";
});
});
});
body {
display: flex;
justify-content: center;
align-items: center;
}
#btn {
display: block;
}
.gridDiv {
background-color: grey;
}
#container {
height: 500px;
width: 500px;
border: 5px solid black;
display: inline-grid;
gap: 1px 1px;
grid-template-columns: repeat(16, auto);
/*grid-template-rows: repeat(auto);*/
}
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8"/>
<title>The Official Odin Project Etch a Sketch</title>
<link rel="stylesheet" href="style.css"/>
<script src = "script.js" defer></script>
</head>
<header></header>
<body>
<div id="btnDiv">
<button id = "btn">Click Me</button>
</div>
<div id = "container">
</div>
</body>
</html>
I am unsure if I have the grid coded in CSS incorrectly or if there is something in JavaScript that I would need to add that will change my grids. I know there are 100s of walkhroughs through the entire project, but I am just really trying to work through it myself and make my code work, not someone elses. Any help would be greatly appreciated, thanks!
I have tried
document.getElementById('container').style.gridTemplateColumns = "uerInput , auto";
It did not work but I am unsure of if the issue is syntax or something else entirely.

You were almost there! "userInput , auto" is being applied to your CSS property literally, so the value ends up being the string "userInput" which is not the number that the user intended to put in.
You probably want to use the repeat() function like this:
document.getElementById('container').style.gridTemplateColumns = `repeat(${userInput}, 1fr)`;

Related

Change text colour on text scroll

I am using the Neve Theme on WordPress for my website development and I am customizing my header block and I am having an issue. I am using a plugin to give my header a background after 100px on scroll of the page this changes the background colour to where the text in the header is difficult to read.
The plugin offers the functionality to change the text colour but Neve overrides anything this plugin or myself can do through it. This way I am wondering if there is a way I can change the text colour through code after 100px of scroll on the website. The classes for the content are as follows
a.button.button-primary & .book-now-header * header.header
header.header is for the entire header block so that is used to change the background colour and the other 2 are for the content needing to change colour.
Any help with this would be appreciated as I am unsure where to begin.
this code below is detect the element scroll postition you can put the result in equation but first change number of position to hex and then use it with color you have and that will change color in your text
let lastPostition = 0;
function myFunction() {
const element = document.getElementById("myDIV");
let x = element.scrollLeft;
let y = element.scrollTop;
document.getElementById ("demo").innerHTML = "Horizontally: " + x.toFixed() + "<br>Vertically: " + y.toFixed();
console.log(lastPostition);
if(y.toFixed() === lastPostition ){
alert("the end of document");
}
lastPostition = y.toFixed()
}
<!DOCTYPE html>
<html>
<style>
#myDIV {
height: 250px;
width: 250px;
overflow: auto;
}
#content {
height: 800px;
width: 2000px;
background-color: coral;
}
</style>
<body>
<h1>The Element Object</h1>
<h2>The scrollTop and scrollLeft Properties</h2>
<p>Scroll the content below to display the number of pixels it is scrolled.</p>
<div id="myDIV" onscroll="myFunction()">
<div id="content">Scroll me!</div>
</div>
<p id="demo"></p>
</body>
</html>
let lastPostition = 0;
function myFunction() {
const element = document.getElementById("myDIV");
let x = element.scrollLeft;
let y = element.scrollTop;
document.getElementById ("demo").innerHTML = "Horizontally: " + x.toFixed() + "<br>Vertically: " + y.toFixed();
if(y.toFixed() === lastPostition ){
alert("the end of document");
}
lastPostition = y.toFixed()
}

Access dynamically added CSS Grid items from parent grid container in grid order using JavaScript?

I have a CSS Grid Layout with no preset columns or rows because the number of items to be added is unknown beforehand. I use JS to create DOM elements and set their column and row numbers. Later, I want to update specific spots in the grid with a new element; before doing so I want to check if there is an element already at that position in the grid and, if so, retrieve and remove it.
To do that I'm looking for something along the lines of a 'containerElement.getElements().gridOrder()' type of deal which would return children elements in an array (or 2D array).
Perhaps I'm looking in the wrong place but I haven't seen anything like this on MDN. Do I need to loop through child elements and use their 'style.gridColumn' and 'style.gridRow' properties to manually sort things?
Here is sample code showing how I'm dynamically adding items to a grid:
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<title>test page</title>
<style>
.box {
width: 30px;
height: 30px;
border-radius: 5px;
background-color: rgb(207,232,220);
margin: 5px;
}
.wrapper {
display: grid;
grid-gap: 20px;
background-color: rgb(79,185,227);
color: #fff;
overflow: auto;
}
</style>
<script>
function run(){
let con = document.getElementsByClassName('wrapper')[0];
for(let i=1; i<10; i++){
let e = document.createElement('div');
e.className = 'box';
e.id = i+"";
e.style.gridColumn = i;
e.style.gridRow = i;
con.appendChild(e);
}
}
</script>
</head>
<body onLoad='run()'>
<h1>Grid</h1>
<div class="wrapper">
</div>
</body>
</html>
I did not find any further information relating to my question so I went ahead with my own suggestion in the post; I just used a standard 2D array to track which spaces were filled or not.
Since arrays in JavaScript are dynamic this only requires checking if a slot contains an existing array for a row-- adding one if it doesn't --and then adding the item at the specified location.

Using document.write removes all other text and displays only the message

I just have a question about how I would make it so that there is a button in one column and when you click the button, text appears in another column. My overall goal is to make a simple clicker.
Here is my code:
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Clicker</title>
<meta name="generator" content="BBEdit 11.6" />
</head>
<body>
<table width=600>
<tr>
<td width=300><span><font size=24px><button onclick='onClick()'>
click me
</button></span></td>
<td sidth=300><span><font size=24px>So does this</span></td>
</tr>
</table>
<script>
clicks = 0;
function onClick () {
clicks = (clicks + 1);
document.write ("you have clicked the button ")
document.write (clicks)
document.write (" times")
};
</script>
</body>
</html>
I have what I need to make it so that you get a message when you click the button, but when I do, all the other text dissipears and I get just that message. Tell me if it was a really stupid mistake or not please. I need to know.
To show the count of clicks in the page, and keep your html, a simple way to achieve that is adding a div and manipulate only its content with getElementById (to get the element) and then call innerHTML (to change the content of an HTML element).
Add this bellow your html table:
<div>
<h1 id=click-event> </h1>
</div>
And change your onClick():
function onClick () {
clicks = (clicks + 1);
document.getElementById("click-event").innerHTML = "you have clicked the button " + clicks + " times";
};
Create an annonymous function when you click the button and call the counting() function. This will increase the value of the variable countingClicks and then set the innerText of the element in the other column to that variable.
var x = document.getElementById("counter");
var y = document.getElementById("display");
var countingClicks = 0;
function counting() {
countingClicks++;
y.innerText ="Number of times clicked: " + countingClicks;
}
//When the counter button is clicked call counting
x.onclick = function(){
counting()
}
.container{
width: 600px;
box-sizing: border-box;
}
.row{
display: flex;
flex-wrap: wrap;
width: 100%;
}
.six{
width: 48.33%;
text-align: center;
border: 1px solid black;
}
<div class="container">
<div class="row">
<div class="six">
<button id="counter">Counter</button>
</div>
<div class="six">
<span id="display"></span>
</div>
</div>
</div>
With peace and love for a confusing question.
<button onclick="a='textContent';t[a]=t[a].replace(/\d+/,++this[a])">0</button><p id=t>Total:0

How to account for user-entered typos in a JavaScript prompt?

First off, hello! I'm new to this website so I apologize for any errors that I make posting-wise.
I am in a web technology class where we are learning JavaScript. In a previous class we learned HTML5 and CSS. Our current assignment is to make a webpage that will either display 1 of 3 images or no images when the user enters the corresponding word in the prompt window.
I was wondering if there was a way to account for user-entered typos? For example, I have in the code "Spn" but was wondering if there was a way to easily make it so that if a user were to enter "Son" by mistake, they would still be shown the image.
Is there a way to do this without having to add a separate if statement?
Below is the code I have so far, which includes my little "test" to see if I could do this. I thought it had worked when I only had two items (ex: "Spn, "spn"), but when I added a third it stopped working, and now it isn't working again. I may have very well been mistaken that there was ever a success, though.
Oh, also, we are only allowed to use JavaScript, HTML, and CSS. So if you have a solution that is jquery (I have no idea what that is), then thank-you, but I'm afraid I can't use it.
Please let me know if there is any other information that you need and I will gladly supply it to you. Thank-you very much for your help, I very much appreciate it!
-Carly
JavaScript Code (file name is switch.js):
var temp = "None";
function choose()
{
temp = prompt("Spn, DW, SH, or None?");
if (temp == "Spn","spn")
{
document.getElementById("picture").src="first.jpg";
document.getElementById("sub").innerHTML="Supernatural";
document.getElementById("picture").style.visibility="visible";
};
if (temp == "DW","dw","Dw")
{
document.getElementById("picture").src="second.jpg";
document.getElementById("sub").innerHTML="Doctor Who";
document.getElementById("picture").style.visibility="visible";
};
if (temp == "SH","sh","Sh")
{
document.getElementById("picture").src="third.jpg";
document.getElementById("sub").innerHTML="Sherlock";
document.getElementById("picture").style.visibility="visible";
};
if (temp == "None","none")
{
document.getElementById("picture").src="blank.jpg";
document.getElementById("sub").innerHTML="Click button to reveal image";
document.getElementById("picture").style.visibility="hidden";
};
}
HTML Code (file name is userchoice.html):
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="switch.js"></script>
<title>What is this not working I'm going to cry</title>
</head>
<body>
<h1>SuperWhoLock</h1>
<h2 id="sub">Click button to reveal image</h2>
<div id="picblock">
<img src="blank.jpg" id="picture">
</div>
<div id="buttons">
<button onclick="choose()">Choose Picture</button>
</div>
</body>
</html>
CSS code (the file name is style.css):
body
{ background-image:url('background.jpg');
}
h1
{ width: 25%;
text-align: center;
margin-left: auto;
margin-right: auto;
background: black;
color: white;
}
h2
{ width: 25%;
text-align: center;
margin-left: auto;
margin-right: auto;
background: white;
color: black;
}
#picblock
{ width: 25%;
text-align: center;
margin-left: auto;
margin-right: auto;
}
#picture
{visibility:hidden;
}
#buttons
{ text-align: center;
margin-left: auto;
margin-right: auto;
}
Barring the foray into putting intelligence in the code, I will give a rather simplistic approach, detailed below:
Since you are the one who is deciding that "Son" should pull up the image ideally meant for "Spn", we should use a mapping that is created by you yourself. We can have something like this:
`
var spn = "Spn", dw ="DW",sh="SH";
//creating a custom mapping
var dict = {
"Son":spn,
"Sln":spn,
"Spn":spn,
"DW":dw,
"DE":dw,
"SH":sh
}
//Your if would look like:
temp = (dict && dict[temp])?dict[temp]:null;
if (temp && temp.toLower() == "spn")
`
2. For creating that dictionary, you will just have to consider the characters around the letter that you are typing.
Note: This approach assumes you have only these three things to compare. If you want a more generic solution that should work beyond Spn,DW,SH, None, please let me know.

How can I return a button to its original color

i have the following code, and I am trying to figure out how can I set the first button to white if I click it once again, same thing for the next button.
So,if i clicked it once it turns red, but if I click again, it turns white.
any ideas.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title> color divs </title>
<meta name="author" content="Lee Middleton" />
<meta name="keywords" content="CIS120/121/122" />
<meta name="description" content="Template for x/html, CSS and JavaScript" />
<style type="text/css">
.container {
border: 1px solid blue;
border-radius: 10px;
width: 100px;
height: 50px;
}
</style>
<script language="javascript">
function changeColor(whichOne)
{
var thatOne = eval(whichOne);
var element = document.getElementById(whichOne);
var color = "ff";
var stringColor;
if (whichOne == 1)
{
stringColor = "#" + color + "0000";
else {
alert('it was clicked') ;
}
}
}
else if (whichOne== 2)
{
stringColor = "#0000" + color;
}
element.style.backgroundColor = stringColor;
}
</script>
<body>
<div class='container' id='1' style='margin: 150px 0 0 75px; float: left;' onclick='changeColor(1);'></div>
<div class='container' id='2' style='margin: 150px 0 0 175px; float: left;' onclick='changeColor(2);'></div>
<div class='container' id='3' style='margin: 150px 0 0 220px; float: left;' onclick='changeColor(3);'></div>
</body>
</html>
As the other solution mentions you could store the previous color in a variable so you can reset it when necessary, but there is an easier way if you just want to return the element to its default colour.
Just do:
element.style.backgroundColor = '';
This just unsets the background-color part of the style attribute, allowing for the color from the css to be used.
So to toggle between default and a colour you can just do this:
element.style.backgroundColor = element.style.backgroundColor ? '' : '#' + color;
You need to save the previous state of the button outside this function like that
var prevColor = "#ffffff";
function changeColor(whichOne) {
prevColour = (this.prevColor=="#ffffff")?"#ff0000":"#ffffff";
// use this prevColour to change button colour
}
1st point
You got some {} closure problem.
Your first if contains an else without an if associated with it.
This same if is close {} but you close it again before the else if
2nd
If I understand right you are having a function to toggle the color of the button base on it's ID.
I would write something similar to this
if(document.getElementById(whichOne).style.backgroundColor==COLOR1)
{
document.getElementById(whichOne).style.backgroundColor = COLOR2
}
else
documenet.getElementById(whichOne).style.backgroundColor = COLOR2
Color 1 and Color 2 and constants in the function, no need to fill the namespace.
Toggle the background-color or which ever attributes you want to manipulate via CSS markup from a toggle event.
Add this class to your CSS
.container {
background-color: #d1d1d1;
}
.colorMe{
background-color: red;
}
Use this script
$(document).ready(function(){
$('.container').on("click", function(){
$(this).toggleClass('colorMe');
});
});
HTML
<div class='container'> Button-1 </div>
<div class='container'> Button-2 </div>
<div class='container'> Button-3 </div>
Dont forget to link a jQuery library.
Here is a live working example: JsFiddle Example
If all you want to do is change the appearance then you should stick to CSS classes. It is this type of inline code that can give you a headache when you go to debug it months down the road when the client wants it to turn pink instead of white.
Likewise on the inline event binding. Javascript can be invoked several ways and it can quickly become a burden keeping track of them all when there are little snippets scattered throughout your HTML.
I recommend something like the following:
HTML
<div class='container green' id='1' ></div>
<div class='container blue' id='2' ></div>
<div class='container yellow' id='3'></div>
STYLES
.container.active { background-color:white;}
JAVASCRIPT
function changeColor(el){
var classes = el.className.split(' '), // get the current classes
index = classes.indexOf('active'), // see if 'active' is one of them
hasClass = index > -1;
if (hasClass)
el.className = (classes.splice(index, 1), classes.join(' ')); // remove 'active' and stringify
else
el.className+= " active";
}
// put all calls that require the DOM to be loaded in a function
function init(){
var divs = document.getElementsByClassName('container'), // get all elements that need binding
divCount = divs.length; // the length of the array for looping
// loop through array
while(divCount--){
// bind each element
// using an anonymous function wrapper to pass 'this' parameter
divs[divCount].addEventListener('click', function() { changeColor(this) });
}
}
// fire the init function once the window is loaded
window.addEventListener('load', init);
http://jsfiddle.net/NpW9X/
You could try this:
JavaScript:
var times = 0;
function isEven(num) {
if (num % 2 == 0) return true;
else return false;
}
function changeColor(whichOne) {
if (isEven(times)) {
document.getElementById(whichOne).style.color = 'white';
} else {
document.getElementById(whichOne).style.color = 'red';
}
times++;
}

Categories

Resources