A fellow noob here. I was wondering how can I make this button print something when pressed, I tried the document.write() but it prints it on a new clear page, I want it to be just like the image I attached.
Any ideas :D
<button onclick = "myVidPlayer.requestPictureInPicture()" " Id="togglePipButton"
>START</button>
If you are refering to print as write to DOM element or console use below code:
const someData = 'the_Data_You_Want_To_Print'
document.getElementById('printButton').onclick = function() {
//print in DOM element
document.getElementById('printHere').innerHTML = someData;
//print on console
console.log(someData)
};
#printHere {
position: absolute;
top: 15%;
left: 6%;
font-size: 5vw;
}
<button id="printButton">Click Me To Print</button>
<p id="printHere"></p>
You could use an alert window.
alert("Hello! I am an alert box!!");
or something like this:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Alert</h2>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
alert("I am an alert box!");
}
</script>
</body>
</html>
Related
I was wondering if I can create a text input where users can type some text and then immediately display them on page, same as twitter. I know about alert window or prompt window but I need something different, a text input on website.
Hope it can be done in JavaScript.
Use .keyup() for the input field then replace the content of the output div.
$(".div-input").keyup(function() {
$(".output").html($(this).val());
});
.output {
margin-top: 20px;
font-size: 2em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="div-input" />
<div class="output">
</div>
If you want to display the input on submit, you could attach a .submit() event on a form tag then use appendTo on the div if you want to insert multiple elements;
$(".form-input").submit(function(e) {
e.preventDefault();
var value = $(".div-input").val();
$("<div class='outputs'>" + value + "</div>").appendTo($(".output"));
});
.output {
margin-top: 20px;
}
.outputs {
padding: 20px;
font-size: 2em;
border: 1px solid black;
margin-bottom: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form-input">
<input class="div-input">
<button type="submit">Submit</button>
</form>
<div class="output"></div>
you can use this to show your text anywhere on page
<input id="input-name" oninput="outputname.value = this.value">
<output id="outputname" name="outputname" for="input-name"></output>
You can test it here
If you add an eventlistener to the input, you can use that to change the text in your output area on the page. Like this:
const input = document.getElementById('input');
const output = document.getElementById('output');
input.addEventListener('input', (e) => {
output.innerHTML = input.value;
});
<div id="output"></div>
<input type="text" id="input">
HTML:
<p>Input:</p><input id="input" type="text">
<p>Output:<span id="output"></span></p>
Javascript:
// Function To Select Element
function $(element) {
return document.querySelector(element);
}
// We will get the input when calling this function
function getInput() {
return $('#input').value;
}
// The output will be displayed
function output() {
$('#output').innerHTML = getInput();
}
// This function will start our code
function init() {
output();
}
// On keyup our code will initiate
$('#input').addEventListener('keyup', init);
You can test it here: https://codepen.io/anon/pen/ReyGaO?editors=1111
People are downvoting you because this can be done with very basic JavaScript, and questions like this are very unusual because anyone doing a basic JavaScipt course will probably be able to do this.
Theoretically speaking: you can put an input element and a button on the html page, plus an empty div. You can set an event for the button or even for the input for live updating while typing, and write an event handler function to change the content of the empty div. You can either set its content or add a new child to it, so that the previous content still remains.
Practical example: (The code below is live at https://codepen.io/bradib0y/pen/YJLGrb )
<!DOCTYPE html>
<html>
<body>
<p>Click the button to add a new post.</p>
<input id="NewPostField" type="text" value="Some text">
<button onclick="myFunction()">Add new post</button>
<div id="Posts"></div>
<script>
function myFunction() {
var NewPostField = document.getElementById("NewPostField");
var newPost = document.createElement("p");
newPost.innerHTML = NewPostField.value;
var Posts = document.getElementById("Posts");
Posts.appendChild(newPost);
}
</script>
</body>
</html>
you can do it by this
<input id="mainInput" oninput="output.value = this.value">
<output id="output" name="output" for="input-name"></output>
click here to view in jsFiddle
This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 4 years ago.
I'm doing the 10 days of JS on Hackerrank and I'm stuck on day 9 where you have to make a button and on each press it increments the number on the button by one. I've written this code but it doesn't seem to do anything. The button looks fine but the onclick doesn't work. I also want to do this without writing something along the lines of onclick="increment()" in the html code because I can already do that. To test my code I went into w3schools.com and found a random test and replaced the code with my own:
var btn = document.getElementById('btn');
var i = 0;
btn.onclick = function() {
i++;
btn.innerHTML = i;
};
.btnClass {
width: 96px;
height: 48px;
font-size: 24px;
background: #4FFF8F;
}
<h2>The Button Element</h2>
<button id="btn" class="btnClass">0</button>
If you want to keep your JS in the head, you can also wrap it in window.onload to keep things tidy.
<!DOCTYPE html>
<html>
<style>
.btnClass {
width: 96px;
height: 48px;
font-size: 24px;
background: #4FFF8F;
}
</style>
<script>
window.onload = function() {
var btn = document.getElementById('btn');
var i = 0;
btn.onclick = function () {
i++;
btn.innerHTML = i;
};
}
</script>
<body>
<h2>The Button Element</h2>
<button id="btn" class="btnClass">0</button>
</body>
</html>
With window.onload, your js will "see" your button, because the page has been fully loaded.
You JavaScript is parsed and executed before your button is in a page. Just move your script below button or attach even that will execute your code once the page is loaded.
Your HTML and Script should look like this:
<!DOCTYPE html>
<html>
<style>
.btnClass {
width: 96px;
height: 48px;
font-size: 24px;
background: #4FFF8F;
}
</style>
<body>
<h2>The Button Element</h2>
<button id="btn" class="btnClass">0</button>
<script>
var btn = document.getElementById('btn');
var i = 0;
btn.onclick = function () {
i++;
btn.innerHTML = i;
};
</script>
</body>
</html>
Your Javascript was being processed before your HTML had been loaded into the DOM (Document Object Model) due to you putting your JS before your HTML...
You could switch this around as the answer from Senad, however... a safer way to execute Javascript which manipulates the DOM is to wait until the DOM has been fully loaded.
Below is some code which fixes your issue by listening out for the DOMContentLoaded event and will work no matter where you load your Javascript.
document.addEventListener('DOMContentLoaded', function(){
console.log("DOM Loaded");
//Wait to add event listeners until the DOM is fully loaded. This is needed
// when wanting to access elements that are later in the HTML than the <script>.
var btn = document.getElementById('btn');
var i = 0;
btn.addEventListener('click', function(el) {
i++;
btn.innerHTML = i;
console.log("clicked")
});
});
I take a look at this link: https://www.w3schools.com/jsref/event_onclick.asp
I think the id inside of your button should be an onclick Event.
Hope this helps.
I can't seem to get this to work at: https://jsfiddle.net/xc6htkn4/4/
<body>
<p id="one">One</p>
<p id="two">Two</p>
<p id="three">Three</p>
<p id="four">Four</p>
<p>
<button onclick="changeId()">Try it</button>
</p>
</body>
#one {
color: red;
}
#two {
color: blue;
}
function changeId() {
var el = document.getElementById('one');
el.id = 'two';
}
What is wrong with the code? It appears to be correct. I am simply trying to change the id on a click event.
Thanks!
Edit: My settings were not appropriately set in jsfiddle
You code is fine, you just need to change the way jsfiddle loads the js code.
Click on "javascript" button and select "Load Type" to be "No wrap - in <body>"
Working example: https://jsfiddle.net/xc6htkn4/5/
I am looking for javascript command that would do the following:
Click on image -> open spoiler
Click on image again -> hide spoiler
Here is what I got so far:
javascript in my html
<script>
function myFunction() {
document.getElementById("prvy").innerHTML = document.getElementById('spoiler_id').style.display='';}
</script>
Spoiler
<a id="show_id"
onclick="document.getElementById('spoiler_id').style.display=''; document.getElementById('show_id').style.display='none';"
class="link"></a><span id="spoiler_id"
style="display: none">[Show]<button onclick="document.getElementById('spoiler_id').style.display='none';
document.getElementById('show_id').style.display='';"
class="link">[Hide]</button>
<br><h1 id="bz">Heading</h1><br><br><p>text</p></span>
And my button:
<div id="prvy" onclick="myFunction()"></div>
What I managed to do, is to click on a image, wich will open spoiler. Hovewer, I've been unable to do the second part, onclick again it will close the spoiler.
I also did serach for solution alredy, nothing worked for me, not even this: Link
I also tired if{} else{} statement but didn't work for me either.
Help would be really appreciated, as I am getting desperate on this one.
You can use jQuery .toggle() to toggle show/hide
$("#prvy").click(function() {
$("#spoiler_id").toggle();
});
Note : You need to include jQuery in your document as
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Working snippet :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="show_id"
onclick="document.getElementById('spoiler_id').style.display=''; document.getElementById('show_id').style.display='none';"
class="link"></a><span id="spoiler_id"
style="display: none">[Show]<button onclick="document.getElementById('spoiler_id').style.display='none';
document.getElementById('show_id').style.display='';"
class="link">[Hide]</button>
<br><h1 id="bz">Heading</h1><br><br><p>text</p></span>
<div id="prvy" onclick="myFunction()">button</div>
<script>
$("#prvy").click(function() {
$("#spoiler_id").toggle();
});
</script>
In the JavaScript where you click the button use the simple jQuery function toggle.
$('#spoiler_id').toggle();
Toggle will hide the element selected if it is currently shown or display the element if it is currently hidden.
you would need some state that flips when the function is called.
like this.
<script>
var state = false;
function myFunction() {
state = !state;
if(state){
//do something
}else{
//do something else
}
}
</script>
Is that all of your code, it would be easier for you and less confusing too if you just gave the buttons an on click function and then called that function in your js.
Can I see all of your html
I am giving an example to concerned question using javascript.
HTML:
<script type="text/javascript">
var permit = 'true';
function showhide() {
var getcont = document.getElementsByClassName('hidshowcont');
if (permit === 'true') {
permit = 'false';
getcont[0].style.display = 'block';
}
else {
permit = 'true';
getcont[0].style.display = 'none';
}
}
</script>
<style type="text/css">
.hidshowcont{
height: 200px;
width: 300px;
border: 1px solid #333333;
display: none;
}
</style>
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR1cSDTn18ufwjuMihttTvCPJOnFY-4hxbPcaOVd87nSPaQakbP9IERaQ" />
<br />
<br />
<div class="hidshowcont">
This is an example of hide and show the container by clicking of an image.
</div>
This will help u much
Why doesn't getElementById(theID) work with innerHTML?
Works:
<p id="demo" onclick="myFunction()">Click me to change my HTML content (innerHTML).</p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed!";
}
</script>
Doesn't work:
<p id="demo" onclick="myFunction()">Click me to change my HTML content (innerHTML).</p>
<script>
function myFunction() {
document.getElementById(theID).innerHTML = "Paragraph changed!";
}
</script>
JSFIDDLE
getElementById(theID) works with style.display:
<style>
h2 {
display: inline;
}
.openclose {
cursor: pointer; /* or: hand; */
margin-left: 1em;
}
.image {
display: none;
}
</style>
<script>
function openClose(theID) {
if (document.getElementById(theID).style.display == "initial") {
document.getElementById(theID).style.display = "none"
document.getElementsByTagName("span")[0].innerHTML = "[+]"
} else {
document.getElementById(theID).style.display = "initial"
document.getElementsByTagName("span")[0].innerHTML = "[–]"
}
}</script>
<h2>Heading - 1st</h2><span class="openclose" onClick="openClose('a1')">[+]</span>
<br /><br /><img id="a1" class="image" src="data:image/png;base64,
iVBORw0KGgoAAAANSUhEUgAAAEAAAABAAgMAAADXB5lNAAAAC
VBMVEX///8AAAD/AADAyZ2wAAAAg0lEQVQ4y73QsQnEMBBE0bFByeVqQlW4BAWa5KpxKZcciK3SA
1IBg4z9E7EvWMTixRJVvQUaShf6kBtQ+ng9SOz4RPxQWF04YraZkHjsWqA158a6CBW7ZsmJ9CTEg
LDhGzF+GvG3gbN1IJsOrQNn0gMJBkCzB8iYNdjQ5usDOMMCvNYFYQmUU1ZqYuIAAAAASUVORK5CY
II=">
<br /><br />
<h2>Heading - 2nd</h2><span class="openclose" onClick="openClose('a2')">[+]</span>
<img id="a2" class="image" src="http://cdn.sstatic.net/stackoverflow/img/favicon.ico">
As tested here.
Additionally is it possible to ambiguate getElementsByTagName("span")[0] to something like getElementsByTagName(theTagName)[theIndexNumber]?
You should pass theID as a parameters.
<p id="demo" onclick="myFunction('demo')">Click me to change my HTML content (innerHTML).</p>
<script>
function myFunction(theID) {
document.getElementById(theID).innerHTML = "Paragraph changed!";
}
</script>
http://jsfiddle.net/c5ae2uwe/
Because you're not using the correct ID ('demo') and instead using a variable which doesn't appear to be set anywhere in your example. Another tip, since you're calling onClick on the p element you can reference it with 'this' instead of doing another document lookup.
this.innerHTML = "Paragraph changed";
Your myFunction is expecting the ID of the element whose content to be changed as a parameter, but you are not passing it
<p id="demo" onclick="myFunction('demo')">Click me to change my HTML content (innerHTML).</p>
<script>
function myFunction(theID) {
document.getElementById(theID).innerHTML = "Paragraph changed!";
}
</script>
Demo: Fiddle
See the below code. the variable "theID" is passed a value of the id of tag. Now this variable is passed to the getElementById() function.
This is just for explanation purpose and this is considered as bad coding.
<p id="demo" onclick="myFunction()">Click me to change my HTML content (innerHTML).</p>
<script>
function myFunction() {
var theID = "demo";
document.getElementById(theID).innerHTML = "Paragraph changed!";
}
</script>
To answer your other question:
Additionally is it possible to ambiguate
getElementsByTagName("span")[0] to something like
getElementsByTagName(theTagName)[theIndexNumber]?
getElementsByTagName() returns an array of elements. Hence you could use something like:
getElementsByTagName(theTagName)[theIndexNumber]
But ensure, the function call has returned atleast one element and the variables "theTagName" and "theIndexNumber" has right values.