function not defined onclick with javascript - javascript

i am trying to play audio file on click of div, and then with the next click of the div pause it. However, I am very new to javascript and the first function isn't even executing, and i don't understand how it isn't defined.
here is my code:
<!DOCTYPE html>
<html>
<head>
<style>
.floating-box {
display: inline-block;
width: 150px;
height: 75px;
margin: 10px;
border: 3px solid #73AD21;
}
.after-box {
clear: left;
border: 3px solid red;
}
.player
</style>
</head>
<script>
var has_been_played = 0;
function playSound() {
var aud=new Audio(file);
aud.play();
var b1 = document.getElementbyId("box" + num);
var b1.has_been_played == true;
}
var b1.has_been_played = pauseAud() {
document.getElementById("box" + num).setAttribute("onClick",
"javascript: pauseAud();");
}
function pauseAud() {
var aud=new Audio(file);
aud.pause();
}
</script>
<body>
<div id="box1" class="floating-box" onclick="playSound('donttalk.mp3');"></div>
<div id="box2" class="floating-box" onclick="playSound('goodvibrations.mp3');"></div>
</body>
</html>
I want it to play the sound, and then once it has been clicked the variable changes to "has_been_played" and the next time you click that div the audio file will pause. (hopefully then, the next you click it it will play again.
Why is it saying that the function playSound is not defined onclick?

You need to add the function to the window like so:
function playSound(){
aud.play();
var b1= document.getElementbyId("box"+num);
var b1.has_been_played == true;
}
window.playSound = playSound;

Related

How to link HTML Element with Python function in Jupyter notebook?

I've written JavaScript code that shows a custom right click menu.
I'd like to know how to trigger Python functions upon my menu items being clicked. These menu items are the divs nested under the div with the class of menu, which consequently is the only element in the body section of my HTML.
The environment I'm using is Jupyter Notebook.
notebook.
import jinja2
from bokeh.embed import components
template = jinja2.Template("""
<!doctype html>
<html>
<head>
<script>
src="http://cdn.pydata.org/bokeh/dev/bokeh-0.13.0.min.js"
var menuDisplayed = false;
var menuBox = null;
window.addEventListener("contextmenu", function() {
var left = arguments[0].clientX;
var top = arguments[0].clientY;
menuBox = window.document.querySelector(".menu");
menuBox.style.left = left + "px";
menuBox.style.top = top + "px";
menuBox.style.display = "block";
arguments[0].preventDefault();
menuDisplayed = true;
}, false);
window.addEventListener("click", function() {
if(menuDisplayed == true){
menuBox.style.display = "none";
}
}, true);
</script>
<style>
.menu
{
width: 150px;
box-shadow: 3px 3px 5px #888888;
border-style: solid;
border-width: 1px;
border-color: grey;
border-radius: 2px;
padding-left: 5px;
padding-right: 5px;
padding-top: 3px;
padding-bottom: 3px;
position: fixed;
display: none;
}
.menu-item
{
height: 20px;
}
.menu-item:hover
{
background-color: #6CB5FF;
cursor: pointer;
}
</style>
</head>
<body>
<div class="menu">
<div class="menu-item">Add Node</div>
<div class="menu-item">Delete Node</div>
<div class="menu-item">Update Node</div>
</div>
</body>
</html>
""")
I think you will get clear understanding and clarity on this with below example easily:
// %%javascript
window.executePython = function(python) {
return new Promise((resolve, reject) => {
var callbacks = {
iopub: {
output: (data) => resolve(data.content.text.trim())
}
};
Jupyter.notebook.kernel.execute(`print(${python})`, callbacks);
});
}
// Use it in any Jupyter JS/HTML cell like this
%%javascript
window.executePython("1 + 1")
.then(result => console.log(result)); // Logs 2
// You can access any defined object/method in the notebook
// I suggest writing a function that returns your data as JSON and just calling the function.

Put image on div randomly using javascript

I am making matching game that images in left and right are different, and users have to find(I put one more image in left side).
My problem is that I cannot call image on where I want. What should I have to fix? Thank you.
<!DOCTYPE html>
<html>
<head>
<style>
img {
position: absolute;
}
div {
position: absolute;
width: 500px;
height: 500px;
}
#leftside {
float: left;
}
#rightside {
float: right;
left: 500px;
border-left: 1px solid black
}
</style>
<script>
var numberOfFaces(5);
var theLeftSide = document.getElementById("leftSide");
function generateFaces() {
var createElement("img");
var position = Math.floor(Math.random() * 500);
img.src = 'http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png';
img.id = 'smileImage';
createElement.setAttribute("height", position);
createElement.setAttribute("width", position);
document.getElementById('leftSide').appendChild(img);
}
</script>
</head>
<body>
<h1>Matching Game</h1>
<p>Click on the extra smiling face on the left.</p>
<div id="leftside"></div>
<div id="rightside"></div>
</body>
</html>
You need to set something to the result of createElement('img'). For example, you can change that line to var img = createElement('img');
You never actually use theLeftSide.
createElement is actually document.createElement.
You never defined the variable createElement. Since we called it img earlier, do so now.
leftSide is not the ID of any element, but leftside is. Change it so that all usages are capitalized the same.
After that, you actually need to call generateFaces. Because the page is loaded top-to-bottom, JavaScript doesn't yet know about the div with the ID of leftSide. You have to wait until the page is finished loading to call the Javascript, and you can do that by adding window.onload = generateFaces to the end of your script.
Here's the final result:
<!DOCTYPE html>
<html>
<head>
<style>
img {
position: absolute;
}
div {
position: absolute;
width: 500px;
height: 500px;
}
#leftside {
float: left;
}
#rightside {
float: right;
left: 500px;
border-left: 1px solid black
}
</style>
<script>
function generateFaces() {
var img = document.createElement('img');
var position = Math.floor(Math.random() * 500);
img.src = 'http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png';
img.id = 'smileImage';
img.setAttribute('height', position);
img.setAttribute('width', position);
document.getElementById('leftSide').appendChild(img);
}
window.onload = generateFaces;
</script>
</head>
<body>
<h1>Matching Game</h1>
<p>Click on the extra smiling face on the left.</p>
<div id="leftSide"></div>
<div id="rightSide"></div>
</body>
</html>

Javascript comparison of audio current time results in endless while loop

I am trying to have a event happen at a current time through an audio file. The following code currently works and successfully plays the audio file:
<html>
<head>
<style>
.titletext {
color: white;
display: block;
position: absolute;
font-size: 50px;
width: 1000px;
margin-left: 150px;
margin-right: 200px;
}
.nametext {
color: white;
display: block;
position: absolute;
font-size: 30px;
width: 600px;
margin-left: 500px;
margin-right: 200px;
margin-top: 600px;
}
.earthphoto {
display: block;
position: absolute;
margin-left: 400px;
margin-top: 150px;
}
</style>
</head>
<body onload="update()">
<script type="text/javascript">
document.body.style.background="black";
var changescene=function(){
var allvariables=Object.keys( window );
if(page===1){
console.log(allvariables);
}
page++;
update();
};
var page=1;
var playsound=function(){
if(page===1){
document.getElementById("sound1").play();
document.getElementById("sound1").addEventListener("ended",function(){changescene();});
}
};
var update=function(){
if(page===1){
document.body.innerHTML="";
var text=document.createElement("p");
var textclass = document.createAttribute("class");
textclass.value="titletext";
text.setAttributeNode(textclass);
text.appendChild(document.createTextNode("Welcome to Mikey's Google Earth Presentation!"));
document.body.appendChild(text);
var text2=document.createElement("p");
text2class=document.createAttribute("class");
text2class.value="nametext";
text2.setAttributeNode(text2class);
text2.appendChild(document.createTextNode("By Mikey Richards"));
document.body.appendChild(text2);
googleearthimage=document.createElement("img");
googleearthimage.setAttribute("src","EARTH.png");
googleearthimage.setAttribute("class","earthphoto");
document.body.appendChild(googleearthimage);
var music=document.createElement("audio");
var musiclink=document.createElement("source");
musiclink.src="Slide1.mp3";
music.appendChild(musiclink);
var musicclass=document.createAttribute("id");
musicclass.value="sound1";
music.setAttributeNode(musicclass);
document.body.appendChild(music);
playsound();
}else if(page===2){
document.body.innerHTML="";
}
};
</script>
</body>
</html>
However, although this works for playing the audio file, when I add this code to run some code when it reaches a certain point, it crashes.
while(document.getElementById("sound1").currentTime<16){
}
//insert code here
I place this code in the playsound function directly after the play function for the audio, so the audio file should be playing. Why does the file crash.
Here is a link to see the result of the file:
http://www.presentation.bugs3.com/presentation.html
You effectively have a while(true){} loop in your code. while executes synchronously, which means that there is no break in the execution loop for anything else to happen, like the audio to advance. You only want to use while if the loop itself modifies the condition while is checking. Depending on exactly what you want to do, i'd use setTimeout or setInterval. If you want to stop it after 16 seconds, I'd do
setTimeout(
function(){document.getElementById("sound1").pause()},
16000)
alternatively
var curInterval = setInterval(
function(){
if(document.getElementById("sound1").currentTime<16)
{
doSomething();
}
else
{
clearInterval(curInterval);
doSomethingElse();
}
},
200) //whatever interval makes sense to you.

JQuery. Facing problems with click events

I was writing code for image flip game in jquery but I am facing some problems with the click events on image in the beginning. The problems are when I click one image and click again the same image it works fine but if I click one image, the image src attribute is added to the img tag and then if I click any other image the src attribute is not added to that one for the first click because the clickCounter has the value 1 then. I employed my own logic (clickCounter). I am new to jquery. You may suggest a better way to do this. Thanks in advance.
Here is my code.
<style>
#main{
height: 500px;
border: 1px solid blue;
margin: auto;
}
.myimg{
width: 100px;
height: 100px;
background: lightblue;
background-position: center center;
margin: 10px;
float: left;
border-radius: 20px;
}
</style>
<body>
<div id="main">
</div>
<button id="add">Add</button>
<script src="jquery-1.11.2.js"></script>
<script>
var clickCounter = 0;
$('#add').click(function(){
addElements(44);
$('#add').attr('disabled', 'true');
});
function addElements(times){
var main = $('#main');
for(j = 1; j <= times; j++){
var i = document.createElement('img');
var img = $(i);
img.click(function(){
// $(this).css('background', 'url(back.png)');
var myImage = $(this);
if(clickCounter == 0){
myImage.attr('src', 'back.png');
myImage.attr('width', '100');
myImage.attr('height', '100');
clickCounter = 1;
}else{
myImage.removeAttr('src');
clickCounter = 0;
}
//alert(clickCounter);
});
img.addClass('myimg');
main.append(img);
}
}
</script>
</body>
JSFiddle
The problem is the shared variable clickCounter which is shared between all the elements.
In this case since you have dynamic elements, you could use event delegation and then use the current src value of the img to set the new one like
$('#add').click(function () {
addElements(44);
$('#add').prop('disabled', true);
});
$('#main').on('click', '.myimg', function () {
$(this).attr('src', function (i, src) {
return src == 'back.png' ? '' : 'back.png';
}).height(100).width(100);
})
function addElements(times) {
var $main = $('#main');
for (j = 1; j <= times; j++) {
$('<img />', {
'class': 'myimg'
}).appendTo($main)
}
}
Demo: Fiddle
Instead of counter, check for 'src' attribute as shown below,
$('#add').click(function(){
addElements(44);
$('#add').attr('disabled', 'true');
});
function addElements(times){
var main = $('#main');
for(j = 1; j <= times; j++){
var i = document.createElement('img');
var img = $(i);
img.click(function(){
// $(this).css('background', 'url(back.png)');
var myImage = $(this);
var attr = $(this).attr('src');
if(typeof attr == typeof undefined){
myImage.attr('src', 'back.png');
myImage.attr('width', '100');
myImage.attr('height', '100');
}else{
myImage.removeAttr('src');
}
//alert(clickCounter);
});
img.addClass('myimg');
main.append(img);
}
}
#main{
height: 500px;
border: 1px solid blue;
margin: auto;
}
.myimg{
width: 100px;
height: 100px;
background: lightblue;
background-position: center center;
margin: 10px;
float: left;
border-radius: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="main">
</div>
<button id="add">Add</button>

Animation without jquery, slide left and right

I am trying to slide a div to the left when I show it and slide it to the right when I hide it, but I don't want to use jQuery. Is there a way to do simple animation and support IE7 and IE8 without using a javascript library?
Here is my show/hide js:
function showHide() {
var Elliot = document.getElementById('Daniel').style.display;
if (Elliot == "block") {
document.getElementById('Daniel').style.display = "none";
} else {
document.getElementById('Daniel').style.display = "block";
};
};
HTML would look like:
click me
<div id="Daniel" style="display:block; width: 300px; height: 50px;">
<!-- some stuff -->
</div>
Below is a function that can get you started:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<style>
#yea {
margin-left: 100px;
height: 100px;
width: 100px;
background: blue;
border: 1px black solid;
}
</style>
</head>
<body>
<div id='yea'></div>
<input type="button" value="Capacity Chart" onclick="animateMe();" >
<script>
function animateLeft(obj, from, to){
if(from >= to){
obj.style.visibility = 'hidden';
return;
}
else {
var box = obj;
box.style.marginLeft = from + "px";
setTimeout(function(){
animateLeft(obj, from + 1, to);
}, 25)
}
}
function animateMe() {
animateLeft(document.getElementById('yea'), 100, 700);
}
</script>
</body>
</html>
https://jsfiddle.net/geh7ewLx/

Categories

Resources