How do I insert Javascript into a web page - javascript

Need help putting this javascript into this HTML code ( i'm new to coding )
<img id="coin"/><br/>
<button id="toss">Toss</button><br/>
<div id="count"></div>
HTML ^
var current = 3;
var elem = document.getElementById('toss');
var intervalId = setInterval( function(){
if( current > 0 ){
elem.innerHTML = "<h1>" + current + "</h1>";
} else {
if( Math.random() > .5 ){
elem.innerHTML = '<img src="http://csgowild.com/assets/images/terrorist.png">';
} else {
elem.innerHTML = '<img src="http://vignette1.wikia.nocookie.net/cswikia/images/4/4c/Csgo_CT_icon_alt.png/revision/latest?cb=20151222191721">';
}
clearInterval( intervalId );
}
current--;
}, 1000 ); // 1000 ms = 1s
Javascript ^

Edit: to make it work on the click of the button not the following changes:
I added an `onclick' event to your button, and I wrapped the intervalId function in another function. setInterval, the way you had it, fired immediately, now it is associated with the press of the button.
Here you go, just put it in a script tag like so, all in your HTML file:
working Fiddle
<img id="coin"/><br/>
<button id="toss" onclick=intervalId();>Toss</button><br/>
<div id="count"></div>
<script>
var current = 3;
var elem = document.getElementById('toss');
var intervalId = function() {setInterval( function(){
if( current > 0 ){
elem.innerHTML = "<h1>" + current + "</h1>";
} else {
if( Math.random() > .5 ){
elem.innerHTML = '<img src="http://csgowild.com/assets/images/terrorist.png">';
} else {
elem.innerHTML = '<img src="http://vignette1.wikia.nocookie.net/cswikia/images/4/4c/Csgo_CT_icon_alt.png/revision/latest?cb=20151222191721">';
}
clearInterval( intervalId );
}
current--;
}, 1000 ); // 1000 ms = 1s
}
</script>
I think you can take it from here
Welcome to coding, and welcome to StackOverflow!

There are two ways to include Javascript (or CSS eg.)
1: Embed it directly into your HTML file
<script>
// Your code here
</script>
This is recommended for small code snippets. If you need much Javascript, possibility number two would make more sense.
2: Include as own file
You can also save your Javascript code as - for example - "script.js" and add
the followig to your HTML file:
<script src="/path/to/script.js"></script>
Remember to use the correct path.

Related

Can't load website on iframe tag using javascript

I am trying to let my iframe tag load a webpage for a give time
HTML:
<div id="banner">
<iframe src="" id="adsm">
</iframe>
</div>
<Button onclick="view()" id="major">watch</button>
The javascript:
function view(){
var presenttime=11;
var nextmine=8;
if(presenttime>=nextmine){
//give a src to the adsm watch section
//start setting for the countdown
var timeLeft = 30;
var timerId = setInterval(countdown,1000);
function countdown(){
var value=document.getElementById("count-down");
document.getElementById("major").onclick="";
if(timeLeft == -1){
clearTimeout(timerId);
document.getElementById("adsm").src="";
document.getElementById("banner").innerHTML="please try later";
}
else{
var link="https://doomdefender.com/e9k6bqg3y?key=7089140f45b4fcfdb51fb18ec1ead1cc";
document.getElementById("adsm").src=link;
document.getElementById("adsm").style.display="block";
timeLeft--;
value.innerHTML = timeLeft + ' seconds remaining';
}
}
}
else{
document.getElementById("adsm").style.display="none";
document.getElementById("banner").innerHTML="please try again later";
}
}
At the end I it doesn't even display anything, I created another project with and tried a similar function and it worked please someone should run the code for me and tell me what's wrong

jquery, while loop running in the background, simultaneous while loops

1) How make that while loop would run in background, and the webpage would respond to user clicks despite while loop.
If I start the characters generating while loop, I am not able to input the data to the "input", because the generating loop occupies all resources. Actually, whenever I click "start", I am getting the message that the webpage is not responding asking if I want to stop it. After choosing "to stop", I see that the characters are generated. Nevertheless, it is very difficult to input the characters to the input field and to stop the program with "stop" trigger, and usually webpage crashes.
2) How to make several jquery while loops to run simultaneously, and additionally, webpage should be responsive and accessible to user.
<!DOCTYPE html>
<html>
<head>
<script src="theme/assets/js/jquery/jquery-2.2.3.min.js"></script>
</head>
<body>
<div id="Start"> <b> Start </b> </div>
<div id="Stop"> <b> Stop </b> </div>
<br><br> <div id="random"> </div>
<br><br> <input id="input" type="text" size="500">
<script>
// how to manage without global variables? how to pass variables to the function
var flag = false;
var charstr = "zxcvbnm,\.\/asdfghjkl;\'qwertyuiop[]\\`ąčęėįšųū90\-ž";
var charstrL = charstr.length;
$("#Start").click( function() {
$("#lesson").text("clicked Start");
flag =true;
$(this).val('flag');
while(flag){
setInterval(function() { // this code is executed every 500 milliseconds:
var rand = Math.random();
var num = Math.floor( ( Math.random() * (charstr.length -1) ) );
$("#lesson").text(charstr[num]);
}, 500);
}//while
}); // $("#Start").click( function() {
$("#Stop").click( function(){
flag=false;
$(this).val('flag');
alert('clicked Stop');
});
</script>
</body>
</html>
You can't make a while loop run in the background if it's doing DOM manipulation, because there's only one main UI thread in browser JavaScript.
You also probably don't want to, because this code:
while (flag) {
setInterval(function() { // this code is executed every 500 milliseconds:
var rand = Math.random();
var num = Math.floor( ( Math.random() * (charstr.length -1) ) );
$("#lesson").text(charstr[num]);
}, 500);
}
continuously adds additional timers to call that code every 500ms. In a very short period of time, your browser will become completely non-responsive.
Just set up setInterval, and have the code inside decide whether to run based on flag:
setInterval(function() { // this code is executed every 500 milliseconds:
if (flag) {
var rand = Math.random();
var num = Math.floor( ( Math.random() * (charstr.length -1) ) );
$("#lesson").text(charstr[num]);
}
}, 500);
You can have several of those, though if you have a lot of them you might consider having fewer and just having them do more than one thing each time.
This is a working example for a program prompting user to input characters utilizing setInterval function instead of while loop. The application is to improve the typing skills.
<!DOCTYPE html>
<html>
<head>
<script src="theme/assets/js/jquery/jquery-2.2.3.min.js"> </script>
</head>
<body>
<div id="Start"> <b> Start </b> </div>
<br><div id="lesson"> </div>
<input id="input" type="text" size="500">
<span id="Stop"> Stop </span>
<span id="Clear">
Clear </span>
<script>
// how to manage without global variables ? how to pass vaiables to the function
var flag = false;
var charstr = "zxcvbnm,\.\/asdfghjkl;\'qwertyuiop[]\\`ąčęėįšųū90\-ž";
var charstrL = charstr.length;
$("#Start").click( function() {
flag =true;
$(this).val('flag');
if(flag){
setInterval( function() { // this code is executed every 500 milliseconds:
if (flag) {
var rand = Math.random();
var num = Math.floor( ( Math.random() * (charstr.length -1) ) );
$("#lesson").text("\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0"+charstr[num]);
} //if (flag) {
}, 500);
} // if (flag)
}); // $("#Start").click( function() {
/*
// does not work, because creates infinite loops, each with 500ms waiting time.
// In miliseconds this accumulates to hours and thousands of loops generated usign while
while(flag){
setInterval(function() { // this code is executed every 500 milliseconds:
var rand = Math.random();
var num = Math.floor( ( Math.random() * (charstr.length -1) ) );
$("#lesson").text(charstr[num]);
}, 500);
}//while */
//
$("#Stop").click( function(){
flag=false;
$(this).val('flag');
});
$("#Clear").click( function(){
$("#input").val('');
$("#lesson").text(' ');
});
</script>
</body>
</html>

How can I slow down this js with setTimeout?

I want to slowly rotate the letters in a string using 2 second pauses.
I'm trying to use setTimeout(function, delay) but it doesn't pause it runs the entire script in under a second. How can I do this?
My code is at https://jsfiddle.net/6un4xhuj/
<html>
<head>
<link type="text/css" href="style.css">
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<h1>JS</h1>
<h2 id='for'>For: String Rotations</h2>
<h3 id='result'>Result:</h3>
<h4></h4>
<span id="end_of_results"></span>
<script src="main.js"></script>
</body>
</html>
js:
'use strict';
function display(string) {
$("span#end_of_results").before( $( "<h4>" + string + "</h4>" ) );
}
var string="rotate me";
for (var i = 0; i <= string.length; i++) {
setTimeout(display(string), 2000);
string=string[0,string.length - 1] + string.slice(0,-1);
}
I get this output but all of it immediately, not step by step.
Get rid of the loop and just recurse the same function passing in the string each time. This code repeats without end so you might want to add a condition as per your requirements.
function thing(string) {
string = string[0, string.length - 1] + string.slice(0,-1);
$("h2#result").html( $( "<h3>" + string + "</h3>" ) );
setTimeout(thing, 2000, string);
}
thing(string);
DEMO
setTimeout takes a function in your argument. In your code setTimeout(display(string), 2000);, you pass the result of invoking the function display(string) into setTimeout. To make this more evident, assign it to a variable like this:
var result = display(string); // undefined
setTimeout(result, 2000); // Not right
You'll need to use something like bind, or just create a function that returns a function:
setTimeout(function () {
// Modify your string here
string=string[0,string.length - 1] + string.slice(0,-1);
display(string)
}, 2000);
setTimeout is async, which means the for loop is completing immediately. Also... you are calling display directly instead of passing the function reference. The same algorithm using callbacks would be like this:
jsfiddle: https://jsfiddle.net/w1x0csp9/
'use strict';
var i = 0;
var string="rotate me";
function display() {
if(i > string.length) {
return;
}
$("span#end_of_results").before( $( "<h4>" + string + "</h4>" ) );
string = string[0,string.length - 1] + string.slice(0,-1);
i++;
setTimeout(display, 2000);
}
display();
I've accepted andy's answer, also based on it, I create this version to only scroll once:
<h1>JS</h1>
<h2 id='for'>For: String Rotation</h2>
<h2 id='result'>Result:</h2>
'use strict';
function rotate(string) {
string = string[0, string.length - 1] + string.slice(0,-1);
$("h2#result").html( $( "<h3>" + string + "</h3>" ) ).animate(100);
rotations+=1
if (rotations > string.length) {
return;
}
setTimeout(rotate, 50, string);
}
var string="rotate this string ";
var rotations=0
rotate(string);
fiddle at https://jsfiddle.net/xb865yw6/3/
You are beginning the 2 second wait immediately for all instances of setTimeout. The simplest way to fix your code is to increase the wait each time you go through your loop:
change this:
setTimeout(display(string), 2000);
to this:
setTimeout(display(string), (i+1)*2000);
Alternatively you could make a single HTML element update on a 2 second interval using setInterval() like this:
<div class="rotating-text"> rotate me</div>
<script>
setInterval(function(){
$('.rotating-text').each(function(){
var string = $(this).text();
string = string[0,string.length - 1] + string.slice(0,-1);
$(this).text(string);
});
}, 2000);
</script>
This example applies to everything with a class rotating-text
http://codepen.io/t3hpwninat0r/pen/eZVYqw
You can use .queue() , .delay()
"use strict";
var elem = $("h2#result");
var string = "rotate this string";
elem.append("<br>" + string)
.queue("_fx", $.map(Array(string.length), function(value) {
return function(next) {
string = string[0,string.length - 1] + string.slice(0,-1);
$(this).delay(2000).queue(function() {
$(this).append("<br>" + string).dequeue();
next()
})
}
})).dequeue("_fx")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<h1>JS</h1>
<h2 id='for'>For: String Rotation</h2>
<h2 id='result'>Result:</h2>

Simple JavaScript image rotator

I have a simple image rotator on a website consisting of 4 images that have to appear for a few seconds before showing the next one. It seems to work on its first cycle but then when it gets back to the first image it doesn't show that one but works again from the second image and so on always missing that image on every cycle.
The function is called using onLoad EH in the body. In the body there is an img with my first image inside it. I'm a noob so please be gentle if I've missed anything out.
Here's what I have...
<body onLoad="sunSlideShow()">
<img src="IMAGES/slider1.gif" alt="slide-show" id="mySlider" width="900">
<body>
var quotes = new Array ("slider2.gif", "slider3.gif" ,"slider4.gif", "slider1.gif");
var i = 0
function sunSlideShow()
{
document.getElementById("mySlider").src = ( "IMAGES/" + quotes[i] );
if (i<4)
{
i++;
}
else
i = 1;
setTimeout("sunSlideShow()", 3000);
}
sunSlideShow()
Change it to this:
else
i = 0;
setTimeout("sunSlideShow()", 3000);
Further to my other answer (which was wrong!)... Try this:
http://jsfiddle.net/pq6Gm/13/
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
setInterval(sunSlideShow,3000);
});
var quotes = [
"http://static.guim.co.uk/sys-images/Guardian/Pix/pictures/2007/07/11/sun128.jpg",
"http://icons.iconarchive.com/icons/robinweatherall/seasonal/128/sun-icon.png",
"http://www.astronomytoday.com/images/sun3.gif",
"http://mariusbancila.ro/blog/wp-content/uploads/2011/08/sun.png"
];
var i = 0;
function sunSlideShow() {
document.getElementById("mySlider").src = quotes[i];
if (i < (quotes.length-1))
{
i++;
}
else
{
i = 0;
}
}
</script>
<body>
<img src="http://mariusbancila.ro/blog/wp-content/uploads/2011/08/sun.png" id="mySlider"/>
</body>
==================================================================
EDIT: This is wrong... please find my other answer on this page.
==================================================================
To start with, I wouldn't use ... you're better off starting the script with jquery once the page is loaded.
Add this to your head section:
<script type="text/javascript">
$(function () {
sunSlideShow();
}
</script>
That will fire the sunSlideShow function once the page is loaded.
Then, you're starting your slideshow with var i = 0... but when you've got to the fourth image, you're setting it to 1?
I would be tempted to use a while loop to achieve what you want.
Something like this:
<script type="text/javascript">
$(function () {
sunSlideShow();
}
var quotes = new Array ("slider2.gif", "slider3.gif" ,"slider4.gif", "slider1.gif");
var i = 0;
function sunSlideShow(){
while (i<4)
{
document.getElementById("mySlider").src = ( "IMAGES/" + quotes[i] );
if (i<4)
{
i++;
}
else
{
i = 0;
}
sleep(3000);
}
}
function sleep(miliseconds){
var currentTime = new Date().getTime();
while (currentTime + miliseconds >= new Date().getTime()){}
}
</script>
This script hasn't been tested... but it should start the sunSlideShow function once the page has loaded and then change the image every 3 seconds.
I too searched the web trying to find a general solution to the problem of rotating an image about its center. I came up with my own solution which works perfectly. The basic concept is simple: rotate the entire context by the desired angle (here called 'tilt'); calculate the image's coordinates in the NEW coordinate system; draw the image; lastly, rotate the context back to its original position. Here's the code:
var xp = rocketX * Math.cos(tilt) - rocketY * Math.sin(tilt);
var yp = rocketX * Math.sin(tilt) + rocketY * Math.cos(tilt);
var a = rocketX - xp;
var c = Math.sqrt(a*a + (rocketY-yp)*(rocketY-yp));
var beta = Math.acos(a/c);
var ap = c * Math.cos(tilt + beta);
var bp = c * Math.sin(tilt + beta);
var newX = rocketX + ap;
var newY = rocketY - bp;
context.rotate(tilt);
context.drawImage(littleRocketImage, newX-9, newY-40);
context.rotate(-tilt);
In the penultimate line, the constants '9' and '40' are half the size of the image; this insures that the rotated image is placed such that its center coincides with the center of the original image.
One warning: I use this only for first quadrant rotations; you'll have to put in the standard tests for the other quadrants that change the signs of the components.
Update: 2021
You can use the light-weight library Ad-rotator.js to setup simple Ad-rotation like this -
<script src="https://cdn.jsdelivr.net/npm/ad-rotator"></script>
<script>
const instance = rotator(
document.getElementById('myelement'), // a DOM element
[ // array of ads
{ url: 'https://site1.com', img: 'https://example/picture1.jpg' },
{ url: 'https://site2.com', img: 'https://example/picture1/picture2.jpg'},
// ...
]
);
</script>
<body onLoad="instance.start()">
<div id="myelement"></div>
<body>
Reference Tutorial

Clear Var or Callback in Javascript

Sorry, i am not sure if I am asking the question correctly. When a date is changed by a user the date count down changes on the page. If the date is changed more than once it flashes all date changes. I guess it is storing the previous information somewhere. I have tried clearing the vars.
var deal_yeax = '';
as I would do in php with no luck
$('#deal_end').focusout(function() {
var deal_end = $("#deal_end").val();
var array = deal_end .split('-');
var deal_montx = array[0];
var deal_dax = array[1];
var deal_yeax = array[2];
deal_montx = deal_montx - 1;
$(function(){
ts = new Date(deal_yeax , deal_montx , deal_dax );
$(".h").countdown({
timestamp : ts,
callback : function(days, hours, minutes, seconds){
message_days = (days);
var message_hours = (hours);
$(".message_hours").text(message_hours + " Hours");
var message_minutes = (minutes);
$(".message_minutes").text(message_minutes + " Minutes");
var message_seconds = (seconds);
// Creat the display
if ( message_days < 1 && message_hours < 1 ) { $(".message_seconds").text(message_seconds + " Seconds"); }
else if ( message_days < 1 && message_hours > 1 ) { }
else if ( message_days == 1 ) { $(".message_days").text(message_days + " Day"); }
else { $(".message_days").text(message_days + " Days"); }
if ( message_days < 1 && message_hours < 1 && message_minutes < 1 && seconds < 1 ) {
$(".hide_my_buy_button").fadeOut("fast");
}
}
});
});
});
Everytime you "focusout" from #deal_end, you'll attach a countdown event to .h. Without knowing exactly how countdown(...) works (It'll be good if you provide the source so we can provide more help!), one way to fix the issue maybe to use JQuery's unbind(...) function to remove existing listeners on an event before adding a new one to it.
Here's an example on the issue:
<!-- HTML -->
<div>
<input id="text" />
<button id="clicker" />
</div>
<!-- Javascript -->
$('#text').focusout(function() {
var text = this.value;
// Everytime #text is "focused out", a new event is registered with #clicker.
$('#clicker').click(function() {
console.log('Value: ' + text);
});
});
... and here's how to solve the issue (It's just one of the many ways. This way is probably not the most elegant but anyhow.)
$('#text').focusout(function() {
var text = this.value;
$('#clicker').unbind('click');
// Everytime #text is "focused out", a new event is registered with #clicker.
$('#clicker').click(function() {
console.log('Value: ' + text);
});
});
Bottom line: It seems focusout(...) is adding a new countdown everytime it is triggered. That might be the problem you're having.
Not sure if this helps? Lemme know.
P.S. JSFiddle to go with it: http://jsfiddle.net/PE9eW/
The problem seems to be with .countdown function that you are using in your code to flash the date changes. When you assign a new count down object to $(".h") the plugin or the function probably assign some event handler or interval to it, but it doesn't seem to clear the old ones when it is called again and that is why it flashing all the dates for each countdown. So you will have to do it manually. I am not sure if you are using an external plugin or is it your own function but what you need to do is to clear the existing events or intervals that is assigned to your element when you call the function. I can be more helpful if you tell me which plugin you are using or maybe show the code if it is your own function. (referring to .countdown() )

Categories