How to access an element created in another function in javascript? - javascript

I have a main button the screen and when I click that button it creates two more buttons, then those two buttons should have their own functionality and click events as well. However, they are created within a function and dont have global variables or ids and I don't know how to access them. Anyone have any suggestions?
//html
<html>
<head>
<link rel="stylesheet" href="index.css">
</head>
<body>
<h1>Dataset Maker</h1>
<button id="create-btn">+ Create Dataset</button>
<script src="index.js"></script>
</body>
</html>
//javascript
document.getElementById("create-btn").addEventListener("click",createDataset)
function createDataset(){
var jsonBtn = document.createElement("Button")
jsonBtn.setAttribute("id", "json-btn")
jsonBtn.innerHTML = "JSON"
document.body.appendChild(jsonBtn)
var csvBtn = document.createElement("Button")
csvBtn.innerHTML = "CSV"
document.body.appendChild(csvBtn)
}
function jsonButton(){
var browseJsonBtn = document.getElementById("json-btn")
browseBtn.innerHTML = "Browse Files"
document.body.appendChild(browseBtn)
}
function csvButton(){
var browseCsvBtn = document.createElement("Button")
browseCsvBtn.innerHTML = "Browse Files"
document.body.appendChild(browseCsvBtn)
}

Create all the three buttons in HTML (putting CSS is your choice)
You can just do display: none to the 2 buttons that are to be invisible and with the help of javascript you can set their display to initial. Add this event to the third button.
Example:
function displayButtons() {
document.getElementById('jsonBtn').style.display = 'initial';
document.getElementById('csvBtn').style.display = 'initial';
}
#jsonBtn,
#csvBtn {
display: none;
}
<button id="createButton" onclick="displayButtons()">
Create Button
</button>
<button id="jsonBtn">
Js button
</button>
<button id="csvBtn">
CSV button
</button>
This is actually better than 'creating' the buttons yourself.

<html>
<head>
<link rel="stylesheet" href="index.css">
<style>
.jbtn, .csv-btn{
background-color: crimson;
color: white;
padding: 5px;
margin: 5px;
}
</style>
</head>
<body>
<h1>Dataset Maker</h1>
<button id="create-btn">+ Create Dataset</button>
<script>
document.getElementById("create-btn").addEventListener("click", createDataset)
function createDataset() {
var jsonBtn = document.createElement("Button")
jsonBtn.setAttribute("id", "json-btn")
jsonBtn.innerHTML = "JSON"
jsonBtn.classList.add("jbtn")
document.body.appendChild(jsonBtn)
var csvBtn = document.createElement("Button")
csvBtn.innerHTML = "CSV"
csvBtn.classList.add("csv-btn")
document.body.appendChild(csvBtn)
}
function jsonButton() {
var browseJsonBtn = document.getElementById("json-btn");
browseBtn.innerHTML = "Browse Files";
document.body.appendChild(browseBtn);
}
function csvButton() {
var browseCsvBtn = document.createElement("Button")
browseCsvBtn.innerHTML = "Browse Files"
document.body.appendChild(browseCsvBtn)
}
</script>
</body>
</html>
jsonBtn.classList.add("jbtn")
using this you can add a class after creating button, which can be used to access the element.

sorry, so long time i didn't work with pure javascript. i just suggest my code in jquery. If you change to jquery, all you js code will replace by code below:
$(document).on('click', '#create-btn', function(){
var btn = $('<button class="json-btn">');
btn.html('JSON');
$('body').append(btn);
btn = $('<button class="csv-btn">');
btn.html('CSV');
$('body').append(btn);
});
$(document).on('click', '.json-btn', function(){
$(this).html('Browse Files'); // dont know exactly what you main here
});
$(document).on('click', '.csv-btn', function(){
$(this).html('Browse Files'); // dont know exactly what you main here
});

Related

Incrementing an HTML button in JS [duplicate]

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.

Tippy.js - Unable to hide a tooltip using the tippy.js documentation function

I'm using tippy.js for tooltips on a website, but it comes to a point when I have to hide them manually with a function (on mobile). However I'm unable to hide it using the built in function hide()
Am I doing something wrong or is the library bugged?
Here's the documentation showing the hide() function.
And here's a snippet of my problem.
var instance = new Tippy('button')
var i = 0;
$(document).on('keyup', function() {
$('.clickcount').html(i);
i++;
var popper = instance.getPopperElement(document.querySelector('.tippy-popper'));
instance.hide(popper)
})
button {
margin: 20px;
}
<link href="https://atomiks.github.io/tippyjs/tippy/tippy.css" rel="stylesheet" />
<script src="https://atomiks.github.io/tippyjs/tippy/tippy.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button title="text">Button with Tippy</button>
<div class="clickcount">Focus the document, then hover the button and press any key to hide it.</div>
Any and all help appreciated!
From the documentation:
Find the element's popper reference by calling the method getPopperElement and passing in the element directly:
You need to pass your element to getPopperElement, not the popup.
var instance = new Tippy('button')
var i = 0;
$(document).on('keyup', function() {
$('.clickcount').html(i);
i++;
var popper = instance.getPopperElement(document.querySelector('button'));
instance.hide(popper)
})
button {
margin: 20px;
}
<link href="https://atomiks.github.io/tippyjs/tippy/tippy.css" rel="stylesheet" />
<script src="https://atomiks.github.io/tippyjs/tippy/tippy.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button title="text">Button with Tippy</button>
<div class="clickcount">Focus the document, then hover the button and press any key to hide it.</div>

javascript - one image,two actions

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

Javascript Background Change Colour

I am trying to learn Javascript on my own. So I gave myself a task: Create a button and with that button I can change the background colour. This is what I have done so far. I assume I don't need to run it under localhost like how we usually do PHP? I only drag the file to Google Chrome. So far, after clicking, it doesnt change colour at all. I also wonder why. Would be grateful if someone could point out my error
exe1.html
<html>
<head>
<link rel="stylesheet" href="layout.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.button').click(function(){
$('body').css('background', '#' + changeColour());
});
});
function changeColour() {
return Math.floor(Math.random()*16777215).toString(16);
}
</script>
</head>
<body>
<div class="buttonClickMe">
<button type="button" onclick="changeColour">Click me</button>
</div>
</body>
layout.css
button
{
background-color: red;
width: 100px;
height: 100px;
}
body
{
text-align: center;
background-color: blue;
}
Looks like you are trying to implement the click event in two ways:
as a HTML attribute
<button type="button" onclick="changeColour">
In order for this way to work, you should use changeColour as a function:
<button type="button" onclick="changeColour()">
via JS
$('.button').click(function(){ ...
This is the wrong selector for button (the . looks for elements by class name). Instead, use button:
$('button').click(function(){ ...
Either method will work and you only need one.
This should work
$(document).ready(function () {
$('.button').click(function () {
changeColour();
});
});
function changeColour() {
var col = Math.floor(Math.random() * 16777215).toString(16);
$('body').css('background', '#' + col);
}
If you are learning javascript don't jump so fast to jQuery, first do it in plain javascript, like this.
Pure JS
var array = ['black','red','yellow']; //create an array with colors
function changes(){ //create the function
document.bgColor= array[Math.floor(Math.random()* array.length)]; //change the document. for example
}
HTML
<button type="button" onclick="change()">Click me</button>
The selector you're using for the click event does not exist. Add a class to the button for it t work.
Try this:
HTML
<button type="button" class="button">Click me</button>
CSS
$(document).ready(function(){
$('.button').on('click', function(){
$('body').css('background', '#' + changeColour());
});
});
function changeColour() {
return Math.floor(Math.random()*16777215).toString(16);
}
What you've done is fine,
You should move the button class .button onto the actual button element and remove the onclick and then should work.
Here:
http://jsfiddle.net/745ex5zc/
$('.button').click(function(){...
is referring to a click on a button with the CLASS button.
Simply add class=""button" to your button and it would work, though I'd recommend using id="myId" and using $('#myId').click(function(){ instead.
Give this a try...
JSFiddle https://jsfiddle.net/w6tjtaqy/
<script>
$(document).ready(function(){
$('.button').click(function(){
$('body').css('background', '#' + changeColour());
});
});
function changeColour() {
return Math.floor(Math.random()*16777215).toString(16);
}
</script>
<style>
button
{
background-color: red;
width: 100px;
height: 100px;
}
body
{
text-align: center;
background-color: blue;
}
</style>
<div class="buttonClickMe">
<button type="button" class="button">Click me</button>
</div>

Remove print button from hard copy

With reference to this link and this, I printing a report using javascript as
<!DOCTYPE html>
<html>
<head>
<script>
function printpage()
{
var data = 'Sample Report<br />Sample Report<br />Sample Report<br />';
var data = data+'<br/><button onclick="window.print()">Print the Report</button>';
myWindow=window.open('','','width=800,height=600');
myWindow.innerWidth = screen.width;
myWindow.innerHeight = screen.height;
myWindow.screenX = 0;
myWindow.screenY = 0;
myWindow.document.write(data);
myWindow.focus();
}
</script>
</head>
<body>
<input type="button" value="Print Preview" onclick="printpage()" />
</body>
</html>
But after printing, the print button still remains at the hard copy. So how to hide the print button in hard copy when printing by using the above function?
Give your button a class, e.g. class="noprint". Then Add a stylesheet for print media to your CSS:
#media print {
/* style sheet for print goes here */
.noprint {
visibility: hidden;
}
}
Details: http://www.w3.org/TR/CSS2/media.html
I just solved this with the following css after assigning id to print button.
<style type="text/css">
#media print {
#myPrntbtn {
display : none;
}
}
</style>
And my button as follows.
<input id ="myPrntbtn" type="button" value="Print" onclick="window.print();" >
Also, you can run javascript function with the following actions...
Hide the button
Print the page using window.print();
Again Show back the button
Piece of code...
<script type="text/javascript">
function printMyPage() {
//Get the print button
var printButton = document.getElementById("myPrntbtn");
//Hide the print button
printButton.style.visibility = 'hidden';
//Print the page content
window.print()
//Show back the print button on web page
printButton.style.visibility = 'visible';
}
</script>
Reference Hide Print button while printing a web page

Categories