Prevent executing JS function on page load - javascript

I'm trying to execute foo function when a button is clicked, how can I prevent running scripts onload, sorry for this question, here's an interactive code, my goal is run the function after button click and then display some divs with data. Thanks!
<html>
<head>
<title>Bitcoin Price</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
</head>
<body>
<h1 id="name"></h1>
<p id="cointime"></p>
<div id="dollar"></div>
<div id="gbp"></div>
<div id="euro"></div>
<h6 id="disc" style="width:50%"></h6>
<br>
<button style="width: 200px" onclick="foo()">Load Data</button>
<script>
$.getJSON(
"https://api.coindesk.com/v1/bpi/currentprice.json",
function foo(data)
{
$("#name").append(data.chartName);
$("#cointime").append(data.time.updated);
$("#dollar").append(data.bpi.USD.rate + ' ' + data.bpi.USD.symbol);
$("#gbp").append(data.bpi.GBP.rate + ' ' + data.bpi.GBP.symbol);
$("#euro").append(data.bpi.EUR.rate + ' ' + data.bpi.EUR.symbol);
$("#disc").append(data.disclaimer);
}
)
</script>
</body>
</html>

Wrap the getJSON call into a function, e.g. refresh, and call the refresh function when clicking the button.
<html>
<head>
<title>Bitcoin Price</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
</head>
<body>
<h1 id="name"></h1>
<p id="cointime"></p>
<div id="dollar"></div>
<div id="gbp"></div>
<div id="euro"></div>
<h6 id="disc" style="width:50%"></h6>
<br>
<button style="width: 200px" onclick="refresh()">Load Data</button>
<script>
function refresh () {
$.getJSON("https://api.coindesk.com/v1/bpi/currentprice.json", function (data) {
$("#name").append(data.chartName);
$("#cointime").append(data.time.updated);
$("#dollar").append(data.bpi.USD.rate + ' ' + data.bpi.USD.symbol);
$("#gbp").append(data.bpi.GBP.rate + ' ' + data.bpi.GBP.symbol);
$("#euro").append(data.bpi.EUR.rate + ' ' + data.bpi.EUR.symbol);
$("#disc").append(data.disclaimer);
})
}
</script>
</body>
</html>
I'd suggest to not mix the HTML with JavaScript, but use addEventListener in the JavaScript side to add the events:
<html>
<head>
<title>Bitcoin Price</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
</head>
<body>
<h1 id="name"></h1>
<p id="cointime"></p>
<div id="dollar"></div>
<div id="gbp"></div>
<div id="euro"></div>
<h6 id="disc" style="width:50%"></h6>
<br>
<button style="width: 200px" id="refreshBtn">Load Data</button>
<script>
document.getElementById("refreshBtn").addEventListener("click", function () {
$.getJSON("https://api.coindesk.com/v1/bpi/currentprice.json", function (data) {
$("#name").append(data.chartName);
$("#cointime").append(data.time.updated);
$("#dollar").append(data.bpi.USD.rate + ' ' + data.bpi.USD.symbol);
$("#gbp").append(data.bpi.GBP.rate + ' ' + data.bpi.GBP.symbol);
$("#euro").append(data.bpi.EUR.rate + ' ' + data.bpi.EUR.symbol);
$("#disc").append(data.disclaimer);
})
});
</script>
</body>
</html>

Related

Unable to add data "innerHTML" to <div> tags using getElementByID()

I'm very new to HTML< Javascript concepts. So kindly go easy on me.
I created 2 tags & want to selectively add data to each div tag using their ID, onload, but the the below code isn't adding "H1" & "h2" to each div tag.
Did i miss something ?
<html>
<head>
<title>Titlehere</title>
<p> Hello></p>
</head>
<body>
<div id="tab1" onload="populatehtmlTab1()">
<p>i1</p>
</div>
<div id="tab2" onload="populatehtmlTab2()">
<p>i2</p>
</div>
<script type="text/javascript">
function populatehtmlTab1() {
document.getElementById(tab1).innerHTML = document.getElementById(tab1).innerHTML + "<p>h1</p>";
}
function populatehtmlTab2() {
document.getElementById(tab2).innerHTML = document.getElementById(tab1).innerHTML + "<p>h2</p>";
}
</script>
</body>
</html>
There are a few things wrong with this. Here is the code amended:
function populatehtmlTab1() {
document.getElementById('tab1').innerHTML = "<p>h1</p>";
}
function populatehtmlTab2() {
document.getElementById('tab2').innerHTML = "<p>h2</p>";
}
function loadHtml(){
populatehtmlTab1();
populatehtmlTab2();
}
<html>
<head>
<title>Titlehere</title>
<p> Hello></p>
</head>
<body onload="loadHtml()">
<div id="tab1" >
<p>i1</p>
</div>
<div id="tab2">
<p>i2</p>
</div>
<script type="text/javascript">
</script>
</body>
</html>
First the element id selector must be a string:
document.getElementById('tab1')
second you just need to assign the innerHTML directly:
document.getElementById('tab2').innerHTML = "<p>h2</p>";
Third you should use onload on the body, I wrapped both your functions into another function in my amended code.
You can use:
<html>
<head>
<title>Titlehere</title>
<p> Hello></p>
</head>
<body>
<div id="tab1" onload="populatehtmlTab1()">
<p>i1</p>
</div>
<div id="tab2" onload="populatehtmlTab2()">
<p>i2</p>
</div>
<script type="text/javascript">
function populatehtmlTab1() {
document.getElementById(tab1).innerHTML = $('#tab1').val() + "<p>h1</p>";
}
function populatehtmlTab2() {
document.getElementById(tab2).innerHTML = $('#tab1').val() + "<p>h2</p>";
}
</script>
</body>
</html>
div elements do not have onload so your functions are not being called.
Use insertAdjacentHTML for the insertion
Pass a string to getElementById.
function populatehtmlTab1() {
document.getElementById("tab1").insertAdjacentHTML("beforeend", "<p>h1</p>");
}
function populatehtmlTab2() {
document.getElementById("tab2").insertAdjacentHTML("beforeend", "<p>h2</p>");
}
document.addEventListener("DOMContentLoaded", function() {
populatehtmlTab1();
populatehtmlTab2();
});
<div id="tab1" onload="populatehtmlTab1()">
<p>i1</p>
</div>
<div id="tab2" onload="populatehtmlTab2()">
<p>i2</p>
</div>
Sorry for mixing jquery
<html>
<head>
<title>Titlehere</title>
<p> Hello></p>
</head>
<body>
<div id="tab1" onload="populatehtmlTab1()">
<p>i1</p>
</div>
<div id="tab2" onload="populatehtmlTab2()">
<p>i2</p>
</div>
<script type="text/javascript">
function populatehtmlTab1() {
document.getElementById(tab1).innerHTML = document.getElementById(tab1).value + "<p>h1</p>";
}
function populatehtmlTab2() {
document.getElementById(tab2).innerHTML = document.getElementById(tab1).value + "<p>h2</p>";
}
</script>
</body>
</html>
If the element 'value' is not detected in 'innerHTML', you can generate variables:
var tab1Value = document.getElementById(tab1).value;

toggle function doesn't work on added input

the toggle function work in descrip and example as shown, but the problem is it does not work when I add a new definition via the input from the user. please help!
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('.descrip').click(function(){
$(this).next('.def').slideToggle("slow");
});
});
function addDef () {
//window.alert (1);
var def= document.getElementById("defInput").value;
//window.alert (def);
document.getElementById("addf").innerHTML += "<div class= 'descrip'> descrip </div>";
document.getElementById("addf").innerHTML += "<div class= 'def'> "+def+" </div>";
$(document).ready(function(){});
}
</script>
</head>
<body>
<div class = "descrip"> descrip</div>
<div class = "def"> example </div>
enter def for apple: <input type= "text" id = "defInput"> </input> <br> <br>
<button onclick="addDef()">ADD</button>
<div id = "addf"> </div>
</body>
</html>
Use event delegation
$(this).on("click", ".descrip", function() {
$(this).next('.def').slideToggle("slow");
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$(this).on("click", ".descrip", function() {
$(this).next('.def').slideToggle("slow");
});
});
function addDef() {
//window.alert (1);
var def = document.getElementById("defInput").value;
//window.alert (def);
document.getElementById("addf").innerHTML += "<div class= 'descrip'> descrip </div>";
document.getElementById("addf").innerHTML += "<div class= 'def'> " + def + " </div>";
}
</script>
</head>
<body>
<div class="descrip">descrip</div>
<div class="def">example</div>
enter def for apple:
<input type="text" id="defInput">
<br>
<br>
<button onclick="addDef()">ADD</button>
<div id="addf"></div>
</body>
</html>

display thumbnails and title youtube api v3 javascript

I use the following code to complete a search by keyword. How can I display just the thumbnails and titles on my web page? I can't figure out how to extract that info from the search results and display it on my page.
<!doctype html>
<html>
<head>
<title>Search</title>
</head>
<body>
<div id="buttons">
<label> <input id="query" value='cats' type="text"/><button id="search-button" onclick="keyWordsearch()">Search</button></label>
</div>
<div id="search-container">
</div>
<script>
function keyWordsearch(){
gapi.client.setApiKey('my_api_key');
gapi.client.load('youtube', 'v3', function() {
makeRequest();
});
}
function makeRequest() {
var q = $('#query').val();
var request = gapi.client.youtube.search.list({
q: q,
part: 'snippet'
});
request.execute(function(response) {
var str = JSON.stringify(response.result);
$('#search-container').html('<pre>' + str + '</pre>');
});
}
</script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"> </script>
</body>
</html>
I figured out one way to do it:
<!doctype html>
<html>
<head>
<title>Search</title>
</head>
<body>
<div id="buttons">
<label> <input id="query" value='cats' type="text"/><button id="search-button" onclick="keyWordsearch()">Search</button></label>
<div id="container">
<h1>Search Results</h1>
<ul id="results"></ul>
</div>
<script>
function keyWordsearch(){
gapi.client.setApiKey('api_key_here');
gapi.client.load('youtube', 'v3', function() {
makeRequest();
});
}
function makeRequest() {
var q = $('#query').val();
var request = gapi.client.youtube.search.list({
q: q,
part: 'snippet',
maxResults: 10
});
request.execute(function(response) {
$('#results').empty()
var srchItems = response.result.items;
$.each(srchItems, function(index, item) {
vidTitle = item.snippet.title;
vidThumburl = item.snippet.thumbnails.default.url;
vidThumbimg = '<pre><img id="thumb" src="'+vidThumburl+'" alt="No Image Available." style="width:204px;height:128px"></pre>';
$('#results').append('<pre>' + vidTitle + vidThumbimg + '</pre>');
})
})
}
</script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"> </script>
</body>
</html>

Write text inside a div from JavaScript?

I have a JavaScript function that uses document.write() to write to the page. My issue is that when I click the button to call the function, document.write() replaces what I already had with what I am writing. Is there a way to write text to a specific div from JavaScript?
Here is my HTML code:
<html>
<head>
<link href="style.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="javascript.js">
</script>
<script>
// Calling the Google Maps API
</script>
<script>
<!-- JavaScript to load Google Maps -->
</script>
</head>
<body>
<div class="content">
<div id="googleMap"></div>
<div id="right_pane_results">hi</div>this -->
<div id="bottom_pane_options">
<button onclick="todaydate();">Try It</button>
</div>
</div>
</body>
...and my JavaScript code (something I got from the internet just to test):
function todaydate() {
var today_date = new Date();
var myyear = today_date.getYear();
var mymonth = today_date.getMonth() + 1;
var mytoday = today_date.getDate();
document.write("<h1>" + myyear + "/" + mymonth + "/"+mytoday + "/h1">);
}
I would like the text to be right below the button. Any help would be appreciated.
Thanks,
Josh
You should avoid document.write. You'd better put your results to another div:
<div id="bottom_pane_options">
<button onclick="todaydate();">Try It</button>
<div id="results"></div> <!-- Added div ! -->
</div>
Then
function todaydate() {
var today_date=new Date();
var myyear=today_date.getYear();
var mymonth=today_date.getMonth() + 1;
var mytoday=today_date.getDate();
document.getElementById('results').innerHTML ="<h1>" + myyear + "/" + mymonth + "/" + mytoday + "</h1>";
}
As you can see, we're writing the results to the results div with .innerHTML.
Hope this helps. Cheers
HTML Code:
<div id="someclass"></div>
JS:
document.getElementById("someclass").innerHTML="<h1>some thing you want</h1>";
To write into a div do the following:
Step-1: Give div an id or classname
<div id="txt"></div>
Step-2. Use .innerHTML in the function:
document.getElementById('txt').innerHTML="HELLO";
You can simply try this...
<!doctype html>
<html>
<head>
<script type="text/javascript" >
function load() {
var div = document.getElementById('data');
div.innerHTML = div.innerHTML + "Write your New Data" + "<br>";
}
</script>
<body onload="load()">
<div id= "data">
Hello... I am old
</div>
</body>
</html>
I am calling this on onload() function you can call as per your beed
You need to tell Javascript to perform the action onload... Try with this:
<script type ="text/javascript">
window.onload = function sayHi(){
document.getElementById('hi').innerHTML = 'Hi';
};
</script>
then on your HTML:
<span id="hi"></span>

JSON data not loading

I am trying to load some data from an API into html. But it is not returning anything. My code is below. I have inspected it with developer tools but no errors. Kindly help please.
<html>
<head>
<style type="text/css">
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.getJSON('http://uapi.staging.simplestream.com//tvplayer/channels/programmes/2013-09-01/referer/tvplayer?format=json',function(data){
$('#content').empty();
$.each(data, function(entryIndex, entry){
var html = '<div class="data">';
html += '<div class="title">' + entry['title'] + '</h3>';
html += '<div class="shortDesc">' + entry['synopsis'] + '</div>';
html += '<div class="duration">' + entry['duration'] + '</div>';
$('#content').append(html);
});
});
return false;
});
</script>
</head>
<body>
<div id="content" style="width:500px; height:800px;">
<div class="ellipsis title"></div>
<div class="ellipsis shortDesc"></div>
<div class="duration"></div>
</div>
</body>
</html>

Categories