can you add src and play in js and html - javascript

This is not working for me. I created script src to my HTML
function eyob1() {
var play1 = document.getElementById("aud").src="eyobmknn/trk1.mp3"
play1.loop = "true";
pley1.play();
}
<!DOCTYPE html>
<html >
<head >
<link rel="stylesheet" href="launch.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div onclick="openeyob();" class="eyob" id="eyob">Eyob Mekonnen</div>
<div id="container">
<div onclick="eyob1();" class="eyob1" id="eyob">01 track 01
<script src="lunch.js"></script>
</body>
</html>
and I can add src but the sound cannot be played

I answared a similar question here: How to play audio loaded via file input
It's possible to change the src attribute using the method SetAtrribute:
function eyob1() {
var play1 = document.getElementById("aud")
play1.settAtribute('src', "eyobmknn/trk1.mp3")
}
But is important to notice that your code does't have a an element with id='audio'. Your script won't work as it is now.
A good start point is here: https://developer.mozilla.org/en-US/docs/Web/Tutorials

Related

InnerHTML- fetching from script

I am trying to display random numbers from 1 to 7. I do not want them to repeat and I want to display every number. I've written my JS code inside script tag. I want to get a random number whenever button is clicked, instead I'm getting error
Uncaught TypeError: Cannot set property 'innerHTML' of null
at grandom (fe.html:48)
at HTMLButtonElement.onclick (fe.html:25)
Below is my code
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Goplan Project Selection</title>
<link rel="canonical" href="https://getbootstrap.com/docs/4.1/examples/sign-in/">
<!-- Bootstrap core CSS -->
<link href="https://getbootstrap.com/docs/4.1/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="jumbotron">
<div class="text-center">
<img src="cissoiree.jpg" width="80px" height="80px">
<h1 style="text-size:300em">Go-Plan</h1></div></div>
<div style="padding-top:20px;" class="text-center">
<button class="btn-lg btn-primary" onclick="grandom()">Click!</button>
<p id="demo"><p>
</div>
<script type="text/javascript">
function grandom()
{
var q=[2,3,1,5,4,7,6];
var x=7;
var i;
x=q.length;
var random;
while(1)
{
random = Math.floor(Math.random()*x);
if(random<=q.length)
break;
}
document.write("<br>");
document.write("Question No : " + q[random] );
if(q.length!=1)
<!--document.write("<input type=button value=click here onclick=grandom();><br>");-->
document.getElementById("demo").innerHTML = q[random];
q.splice(random,1);
document.write("<br>");
}
</script>
</body>
</html>
After document.write(...); there is no other elements in the page expect the passed text.
It is why when you trying to find then document.getElementById("demo") it's cannot find, and return null. (then throw error, when you trying to access its innerHTML)
If you trying to append something to the page you should use document.body.innerHTML += "...".
About the algorithm itself - you can use:
[1,2,3,4,5,6,7].sort(function() { return .5 -Math.random();});
It will shuffle the array randomly.
Your document.write(..) is breaking it.
You can try:
document.body.innerHTML += '<br />';
document.getElementById("demo").innerHTML = `Question No : ${q[random]}`;
document.body.innerHTML += '<br />';

TypeError: Cannot read property of null [while calling external(defer)/internal JSFile]

The Html/JS(vanilla) script below ,gives the following error [when used with both an internal script aswell as an external JS file (using the "defer" keyword)] -
How could this error be resolved?
Chrome
Uncaught TypeError: Cannot read property 'onclick' of null
Firefox
TypeError: document.getElementById(...) is null
//StackOverflow Error - Filename empty (Not sure how to insert JS filename?).But this script works fine on Local codeeditor(VsCode).
document.getElementById("change1").onclick(function(){
document.getElementById("tx1").innerHTML = "tx1 changed with JS";
console.log("Change1 btn pressed");
}
)
document.querySelector("change2").addeventlistener("click",()=>{
document.getElementById("tx2").innerHTML = "tx2 changed with JS";
console.log("Change2 btn pressed");
},false
)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=<<device-width>>, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Event2</title>
<script src= "testJS_event2.js" defer ></script>
</head>
<body>
<div>
<p id="tx1">tx1 <--- this element is null </p>
<h1 id="tx2">tx2 <--- this element is also null </h1><br>
<button id = "change1">Change1</button>
<button id = "change2">Change2</button>
</div>
</body>
</html>
You need to assign function to the onclick event attribute of the element
For querySelector you need to access the element with a # as you are accessing the element with its id
There was a typo for addEventListener
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=<<device-width>>, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Event2</title>
<script defer="defer">
window.onload = function() {
//StackOverflow Error - Filename empty (Not sure how to insert JS filename?).But this script works fine on Local codeeditor(VsCode).
document.getElementById("change1").onclick = function() {
document.getElementById("tx1").innerHTML = "tx1 changed with JS";
console.log("Change2 btn pressed");
};
document.querySelector("#change2").addEventListener("click", () => {
document.getElementById("tx2").innerHTML = "tx2 changed with JS";
console.log("Change2 btn pressed");
}, false);
}
</script>
</head>
<body>
<div>
<p id="tx1">tx1
<!--- this element is null-->
</p>
<h1 id="tx2">tx2
<!--- this element is also null -->
</h1>
<br>
<button id="change1">Change1</button>
<button id="change2">Change2</button>
</div>
</body>
</html>
Though defer is used and document is parsed, the defer script will fire before DOMContentLoaded, hence the error.
This Boolean attribute is set to indicate to a browser that the script
is meant to be executed after the document has been parsed, but before
firing DOMContentLoaded.
Scripts with the defer attribute will prevent the DOMContentLoaded
event from firing until the script has loaded and finished evaluating.
Your problem is that the Javascript is executed before you page is fully load, so it can find your elements.
Use window.onload() and it will be good !
Or you can put your <script src= "testJS_event2.js" defer ></script> at the end of your body (better solution for loading time)
You have typo in your code, addEventListener not addeventlistener.
getElementById returns HTMLElement or undefined. HTMLElement does not have onclick property, You need to bind a click event listener to it.
Lastly, you can only query the DOM once it is fully loaded. You JS execute before the code DOM is loaded. That is why the DOM elements your are querying are null/undefined.
You can also bind the onlick event in your butto directly. Here is a working sample code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Event2</title>
<script src="testJS_event2.js"></script>
</head>
<body>
<div>
<p id="tx1">tx1 <--- this element is null </p>
<h1 id="tx2">tx2 <--- this element is also null </h1> <br>
<button id="change1">Change1</button>
<button id="change2">Change2</button>
<button onclick="change3()">Change3</button>
</div>
</body>
</html>
window.onload = function() {
document.getElementById("change1").addEventListener("click", function() {
document.getElementById("tx1").innerHTML = "tx1 changed with JS";
console.log("Change1 btn pressed");
});
document.querySelector("#change2").addEventListener("click", function() {
document.getElementById("tx2").innerHTML = "tx2 changed with JS";
console.log("Change2 btn pressed");
});
};
function change3() {
console.log("Change 3 clicked .......");
}

How to add event with Javascript to an html tag

I've a landingpage with dynamic html tags.
The Problem is, that i can't select directly the tag. Its a link.
the following code is the construct:
<div id="testid"><div><div>Button 1<div><div><div>
Every time someone clicks on the link (a-tag) I want to fire an event like the following code:
Button 1
the question: what is the Javascript code to add the onclick="dataLayer.push({'event': 'button1-click'}) attribute to the a tag.
I tried the following code:
var d = document.getElementById("testid").firstchild;
d.setAttribute("onclick", "dataLayer.push({'event': 'button1-click'})");
but it seems to the code is incorrect. The a tag is also not the first child; there are 2 divs between :(
Use querySelector and addEventListener:
document.addEventListener('DOMContentLoaded', function () {
var dataLayer = [];
var d = document.querySelector("#testid a[name=button1]");
d.addEventListener("click", function () {
dataLayer.push({ 'event': 'button1-click' });
});
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="testid">
<div>
<div>
Button 1
<div>
<div>
<div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="script.js">
</script>
</body>
</html>
There's a few things you were missing from your JS.
Using a more specific selector (#testid a[name=button1] vs. the firstchild of #testid, which was not accurate).
Wrapping all the code in a DOMContentLoaded listener. JS that depends on elements on a page needs to wait for the page to build first, that's what DOMContentLoaded is.
Check out my solution. Hope this helps.
var d = document.querySelector("#testid a");
var dataLayer = []
d.onclick = function () {
dataLayer.push({'event': 'button1-click'})
console.log(dataLayer.length)
}
<div id="testid"><div><div>Button 1<div><div><div>

Dynamically change the video id on youtube

I am trying to display youtube audio without video with the below code so I am changing the video id but it is playing the same id again and again.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>About</title>
<script type="text/javascript">
function val1(val)
{
document.getElementsByTagName("div")[0].setAttribute("data-video", val);
alert(val);
}
</script>
</head>
<body onload="val1('WKV_z36pVAk')">
<h3 style="color:#0066dd">Hello</h3>
<center>
<div data-video="8IYzyTYucKQ"
data-autoplay="0"
data-loop="1"
id="youtube-audio">
</div>
</center>
<button>change</button>
</body>
<script src="https://www.youtube.com/iframe_api"></script>
<script src="https://cdn.rawgit.com/labnol/files/master/yt.js"></script>
</html>
Not quite sure what you are trying to create, but this might head you into the right direction.
You can reload the specific element in a kind of hacky way using this code
function reload(vidId){ <-- Added a parameter
var container = document.getElementById("youtube-audio");
container.setAttribute("data-video", vidId); <-- Added line to change data-video
var content = container.innerHTML;
container.innerHTML= content;
}
And then add this to your HTML
<button onclick="reload('8IYzyTYucKQ')">Reload</button> <-- Added the parameter to what the `data-video` should be changed

How to use external Javascript to use onclick event to change document.title?

This code runs immediately once the page is loaded. The onclick event is completely ignored by javascript. What is an easy fix for this because like youtube when you play a video the document.title is updated with a speaker. I want to learn to do that with external javascript because I can do it with internal javascript in the html.
<!DOCTYPE html>
<html>
<head>
<title> Animation </title>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="animationcss.css">
</head>
<body>
<script src="animation.js"></script>
<input id="changeButton" type="button" value="Change" ></input>
/External Javascript/
var element = document.getElementById("changeButton");
element.onclick = textChange("changetothis");
function textChange(text){
document.title = text;
}
try calling the function after the document is loaded by placing the script tag below the object or making $(document).ready() function,
this code works fine with me
<!DOCTYPE html>
<html>
<head>
<title> Animation </title>
<meta charset="UTF-8">
</head>
<body>
<input id="changeButton" type="button" value="Change" ></input>
<script src="script.js"></script>
<body>
</html>
and the script is
var el = document.getElementById("changeButton");
el.onclick = function(){
textChange("changetothis");
}
function textChange(text){
document.title = text;
}
You can achieve your desired effect by using an anonymous function, like so:
document.getElementById("changeButton").onclick = function () {
document.title = newTitle;
}
The variable 'newTitle' should be declared & initalized above this code somewhere in order for it to work.

Categories

Resources