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

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

Related

Resizing grids with 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)`;

jQuery Event listeners sticking/cascading?

On my web app, I have a screen that expects a user to use a bar-code scanner to scan an item number in, but in the event they do not have one (or the code won't scan) they can click on the notification that asks them to scan and it changes to a box allowing them to enter the details to search manually.
The issue is, the event listener seems to get applied to the close button, it gets removed from the div but the close button seems to call the "open search box" function instead of the "close search box" function
I tried using the jQuery $('#id').one('click' function(){myFunctionHere();}); function to add an event listener on click of the DIV and also tried using $('#id').on('click' function(){myFunctionHere();}); and $('#id').off('click'); but I have the same issue.
See the jsfiddle
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<style>
#tnt-searchScan{
width: 300px;
height: 100px;
border: 5px dashed red;
text-align: center;
}
</style>
<script>
$(document).ready(function(){
$('#tnt-searchScan').one('click', function(){showSearchBox();});
})
function closeSearchBox(){
var html = '<h4>Scan barcode</h4><h4>or click here to search</h4>';
$('#tnt-searchScan').html(html).one('click', function(){showSearchBox();});
}
function showSearchBox(){
console.log('test');
var html = 'Content of search box<button type="button" id="tnt-closeSearchBox">Close</button>';
$('#tnt-searchScan').html(html);
$('#tnt-closeSearchBox').one('click', function(){closeSearchBox();});
}
</script>
</head>
<body>
<div id="tnt-searchScan"><h4>Scan barcode</h4><h4>or click here to search</h4></div><div id="tnt-mainPage"><div class="loader"></div> </div>
</body>
I expect the box to return back to normal, but it does not, if you check the console, every time you click 'Close' "test" appears, signalling that the show function is called. if i call the "closeSearchBox();" manually it works fine.
You need to make some changes in your js. First of all .one is changed to .on second need to change the close function click event because the search form is added with js to dom so you need to fire click event on it like this $(document).on('click','#tnt-closeSearchBox', function(){ closeSearchBox(); });.
$(document).ready(function(){
$('#tnt-searchScan').on('click', function(){showSearchBox();});
})
function closeSearchBox(){
var html = '<h4>Scan barcode</h4><h4>or click here to search</h4>';
$('#tnt-searchScan').html(html).on('click', function(){showSearchBox();});
}
function showSearchBox(){
//console.log('test');
var html = '<label>Search By: <select id="tnt-searchOption">' +
'<option selected>ID</option>' +
'<option>Legacy ID</option>' +
'</select></label>' +
'<label>Search: <input type="text" id="tnt-searchBox"></label>' +
'<button type="button">Search</button><button type="button" id="tnt-closeSearchBox">Close</button>';
$('#tnt-searchScan').html(html);
}
$(document).on('click','#tnt-closeSearchBox', function(){closeSearchBox();});
#tnt-searchScan{
width: 300px;
height: 100px;
border: 5px dashed red;
text-align: center;
}
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
</head>
<body>
<div id="tnt-searchScan"><h4>Scan barcode</h4><h4>or click here to search</h4></div><div id="tnt-mainPage"><div class="loader"></div> </div>
</body>

How do I append user input? jQuery

I'm trying to create a to-do list. When I open up the html file (I'm using Google Chrome), there seem to be two issues:
The button doesn't appear to be a button, as in it doesn't click.
When I press enter instead of trying to click the add button, the text just disappears.
But in both cases, neither method appends the user input. What do I need to fix?
I have the following:
$(document).ready(function() {
$('#button').click(function() {
var toAdd = $('input[name=checkListItem]').val();
$('.list').append("<div class='item'>" + toAdd + "</div>");
});
});
h2 {
font-family: arial;
}
form {
display: inline-block;
}
#button {
display: inline-block;
height: 20px;
width: 70px;
background-color: #cc0000;
font-family: arial;
font-weight: bold;
color: #ffffff;
border-radius: 5px;
text-align: center;
margin-top: 2px;
}
.list {
font-family: garamond;
color: #cc0000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<h2>To Do</h2>
<form name="checkListForm">
<input type="text" name="checkListItem" />
</form>
<div id="button">Add!</div>
<br/>
<div class="list"></div>
Giving something the id of button does not make it a button. Maybe you should try: <button id="button>Add!</button>
When you press enter you are submitting the form, since you don't have any javascript intercepting the onSubmit event for the form it reloads the page.
If you want this action to happen when the user hits Enter, then you should move the button inside of the form and change the event to $('form[name="checkListForm"]').on('submit', ...)
Ok so I see a few problems here. First of all a div is not a button. I mean you could maybe do styling to make it look like a button, but why not just use:
<button type="button"> Add </button>
Also, you could just use onclick instead of defining that click event. I find this usually cleaner:
<button type="button" onclick="the_function();"> Add </button>
And then in your javascript define the function:
function the_function()
{
var toAdd = $('input[name=checkListItem]').val();
$('.list').append("<div class='item'>" + toAdd + "</div>");
});
However, you are better off putting an id on the input like this:
<input type="text" id="check-list-input" name="checkListItem"/>
Obviously you don't need to use that naming convention. After doing that then you can revise that function to:
function the_function()
{
var toAdd = $('#check-list-input').val();
$('.list').append("<div class='item'>" + toAdd + "</div>");
});
But yet this still isn't as good as it should be. The list should also be an id not a class. If you had more than one list on the page, it would cause problems. Instead do this:
<div class="list" id="list-div"></div>
And then you can revise your function to:
function the_function()
{
var toAdd = $('#check-list-input').val();
$('#list-div').append("<div class='item'>" + toAdd + "</div>");
});
So the end result should be:
<!DOCTYPE html>
<html>
<head>
<title>To Do</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css"/>
<script type="text/javascript" src="script.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<h2>To Do</h2>
<form name="checkListForm">
<input type="text" id="check-list-input" name="checkListItem"/>
</form>
<button type="button" onclick="the_function();"> Add </button>
<br/>
<div class="list" id="list-div"></div>
</body>
</html>
and for your jQuery (no need for document ready anymore, just be sure to include the javascript file or snippet before the html):
function the_function()
{
var toAdd = $('#check-list-input').val();
$('#list-div').append("<div class='item'>" + toAdd + "</div>");
});
I didn't test this yet, but I hope it works for you.

How to create a function in which a box moves in accordance with 2 user inputs (direction and # of pixels to move)

Here's what I have so far:
The following is my CSS for the box:
p
{
width: 100px;
padding: 25px;
border: 25px solid red;
margin: 25px;
position: fixed;
top: 100px;
}
And here is the JavaScript and HTML I have so far:
<!DOCTYPE html>
<html>
<head>
<title>Box Mover</title>
<link rel="stylesheet"; style="text/css"; href="style.css">
</head>
<script>
function initialize()
{
var positionBox = document.getElementById("positionBox");
positionBox = addEventListener("click", moveBox);
}
function moveBox()
{
var positionBox = document.getElementById("positionBox");
positionBox.style.position = "absolute";
}
</script>
<body>
<p>This is a box.</p>
<form>
Number of pixels to move:
<input id="numPixels">
<br>
<br>
Direction to move:
<select id="directionSelection">
<option>Up</option>
<option>Down</option>
<option>Left</option>
<option>Right</option>
</select>
<br>
<br>
<input id="positionBox" type="button" value="Move Box">
</form>
</body>
</html>
The part I am stumped on is how I can get my positionBox button to interact with my directionSelection drop-down menu and numPixels within my JavaScript. Could someone help me out here?
In my class yesterday, my prof showed us an example of getting a button to move with hard-coded parameters, but now I need to do that with a box, making it move in the direction the user specifies, along with the number of pixels to move. I could also post that example code if it could be helpful to anyone.
The part I am stumped on is how I can get my positionBox button to interact with my directionSelection drop-down menu and numPixels within my JavaScript
In your moveBox function, use document.getElementById("numPixels").value and document.getElementById("directionSelection").value to get the number of pixels and the direction to move.
showed us an example of getting a button to move with hard-coded parameters, but now I need to do that with a box
To be able to move the box from your moveBox function, you will need to add an id attr to the <p>This is a box.</p> element so that you can select it with var box = document.getElementById("myBox");. Then, apply the values to box.style.top and box.style.left to move the box around instead of applying the values to the positionBox.

Can each new click produce a new image?

I know how to make an image appear using onclick or onMouseOver but how can I make each click produce the appropriate image not just in the same place but, for example, in a row, next to it's previous apperance? My idea is this: I click on reference1 and a picture1 shows up. Then I click on reference2 and a picture2 shows up next to the picture1 already displayed. Now I click on reference1 again, and I want to see pictures 1,2,1 in a row. How can I do that? My ideal would be to see the row rolling when filled, and a delete button deleting the last image in that row, even making the pictures jump out being called from the text field, but I can search for these myself. My greatest concern for now is new click=new image. Thank you.
Assuming this is relatively simplistic- you could keep track of the current position in a list of images, afterwards create a function that deals with the current image then increments this position. Have the onClick event call this function, and there you are.
An example of this in action, using JQuery, can be viewed here:
http://jsfiddle.net/8Q4LQ/
Here's an example.
<html>
<head>
<style>
.refimg { width: 100px; height: 100px; }
.choices a { margin-right: 2ex; }
.choices img { display: none; }
#target { display:block; width: 500px; overflow-x: scroll; border: 1px solid black; }
</style>
</head>
<body>
Choices:
<div class="choices">
ref1
ref2
<image id="image1" src="image1.gif" class="refimg" />
<image id="image2" src="image2.gif" class="refimg" />
</div>
<br />
Selections: <input type="button" value="Delete" onclick="delImage()" />
<nobr id="target">
</nobr>
<script>
function putImage(src) {
var a = src.cloneNode(true);
a.id = ''; //clear id to prevent duplicate id
target.appendChild(a);
a.scrollIntoView(true);
return false;
}
function delImage() {
var a=target.children;
if (a.length>0) target.removeChild(a[a.length-1]);
}
target.style.height=((target.offsetHeight-target.clientHeight)+100)+'px'; //extend height for scroll bar
</script>
</body>
</html>

Categories

Resources