In the below html, the front button doesn't respond while the back button changes the content of the tag.
<!DOCTYPE html>
<html>
<body>
<p id ="para">Initial text. </p>
<button onClick=document.getElementById('para').innerHTML="move front">
front
</button>
<button onClick=document.getElementById('para').innerHTML="back">
back
</button>
</body>
</html>
In the below, both the buttons change the content of the tag.
<!DOCTYPE html>
<html>
<body>
<p id ="para">Initial text. </p>
<button onClick=document.getElementById('para').innerHTML="movefront">
front
</button>
<button onClick=document.getElementById('para').innerHTML="back">
back
</button>
</body>
</html>
Why does a bank space make a button unresponsive?
That is just invalid HTML.
You have to put quotes around your whole onclick attribute value, otherwise it will end at the space.
onClick = document.getElementById('para').innerHTML="move // cut off here
front" // a second (meaningless) attribute for your button tag.
Please consider this syntax:
<button onclick="document.getElementById('para').innerHTML='move front'">front</button>
You are probably having issues if you are using this technique.
I am sorry but this is not how you attach a click event to elements in modern javascript, at least if you want to work with what's called "good practices".
The better method would be to attach a click event to a desired element using javascript.
I will give you a short code example.
First the HTML - I will use your original HTML (modified a bit):
<!DOCTYPE html>
<html>
<body>
<p id ="para">Initial text. </p>
<button id="frontBtn"> front </button>
<button id="backBtn"> back </button>
</body>
</html>
As you can see, I have removed your "onclick" events from the buttons, and assigned an id to each button.
Second, we will write some javascript to properly attach a click event to each one of the buttons, and of course execute the change of text as you originally was intending to do:
if you are familiar with jQuery then this will do:
$('#frontBtn').on('click',function(){
$('#para').html('move front');
});
$('#backBtn').on('click',function(){
$('#para').html('back');
});
This can also be done with vanilla (native) javascript:
document.getElementById("frontBtn").addEventListener("click", function(){
document.getElementById("para").innerHTML = "move front";
});
document.getElementById("backBtn").addEventListener("click", function(){
document.getElementById("para").innerHTML = "back";
});
Now we have a nicely structured event handler for each button, more code can be easily added.
As for where to insert your javascript ?
You can add the javascript to your html document by using script tags in your html document head like this:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
// your code here..
</script>
</head>
<body>
....
....
Or even better - create a separate script file and load it at the bottom of your html page like this:
<!DOCTYPE html>
<html>
<head>
....
</head>
<body>
....
....
<script type="text/javascript" src="scripts.js"></script>
</body>
</html>
This is the better way to attach events to elements, using javascript.
Imagine if you try to write 50-100 lines of code inline ? impossible! but with an event handler function you can do it easily.
Things will basically work better and your project will be much easier for you to maintain.
Hope it helps a bit!
Related
I wrote HTML document and linked to my JS document.
when I execute the HTML file on my browser it only shows the "Click me!" button, but what I expected it to do was to show the result of my math function when clicked. But .. nothing happens. I'm very new to JavaScript so I'm sure this is a simple answer, but Googling isn't helping ... I appreciate any insight to what I'm doing wrong here.
Here's the code from HTML file:
<!DOCTYPE html>
<html lang=""en">
<head>
<meta charset="UTF-8">
<script src="JS/main.js"></script>
</head>
<body>
<p id="Math">
<button onclick="myFunction()">Click me!</button>
</p>
</body>
</html>
Here's the JS file:
function myFunction(a, b) {return a * b;}
document.getElementById("Math") .innerHTML = myFunction(13, 4);
Not sure what are you trying to do, but if you want to change the content of the "Math" element, you must call the function with parameters (eg: onclick="myFunction(1,3)") and that function should replace the content:
function myFunction(a, b) {
document.getElementById("Math").innerHTML = a * b;
}
<p id="Math">
<button onclick="myFunction(3,4)">Click me!</button>
</p>
Also if you want to preserve the button after clicking, this should be located outside the "Math" element to avoid being removed when replacing innerHTML
You’re including you script file in the header, so it runs before the dom is available. When it executes, it won’t be able to find your id, so nothing will happen. You likely will see an error in the console that your document.getElementById call is returning undefined. Either include it at the end of the body, or add a defer tag:
<script src="JS/main.js" defer></script>
Also, as soon as the code runs, it overwrites the content of the p tag, including the button. Make the p and the button siblings.
One error in your html appears to be caused by an extra " in your lang attribute for your opening html tag. Try deleting it.
<html lang="en">
I am trying to run a javascript inside of a div tag because i have heard its possible but for some reason the code does nothing.
<!DOCTYPE html>
<html>
<body>
<title>XDSITE</title>
<br>
<br>
<div id=mycode style="BACKGROUND:
url('javascript:eval(window.alert("sometext"))'"></div>
</body>
</html>
You have some problems in your HTML it is not valid, you can't run JavaScript from a style attribute.
You can run Javascript from within a <script> tag which really is the best way to do it.
<script>
document.getElementById("demo").innerHTML = "Hello JavaScript!";
</script>
Alternatively there are some HTML elements that allow you to execute it on some events, like onchange, onclick etc.
<select onchange="myFunction()">
<button onclick="myFunction()">Click me</button>
https://www.w3schools.com/ is a great resource for learning more about each html element, and also JavaScript as a whole.
Good luck
can you please tell here which java script framework is you are using? you can achieve this by using and template java script framework like Angular, React...
If u dont want to use any framework than you need to write pure javascript or jquery code for assigning the background css prop.
for entire body,
document.body.style.backgroundImage = "url('img_tree.png')";
for div,
document.getElementById("mycode").style.backgroundImage = "url('img_tree.png')";
<!-- U have to give event inside expression like onclick ,mouseup Click that text -->
<div id=mycode onclick="alert('Hi ....sometext')">THARA
</div>
<!DOCTYPE html> <html> <body> <title>XDSITE</title> <br> <br> <div id=mycode style="BACKGROUND: url('javascript:eval(window.alert("sometext"))'"></div> </body> </html>
Answer :
Open script in footer
<script>
$( "#mycode" ).click(function() {
alert( "Hai" );
});
</script>
I hope its working for you ...
You can target HTML tag using getElementById() and then apply custom style like this
document.getElementById("Mydiv").style.backgroundColor="#0000"
or apply a bunch of styles like this
var dev = document.getElementById("Mydiv");
dev.style.backgroundColor="#0000";
dev.style.fontSize="..";
dev.style.backgroundImage="..";
You can run your function using "onerror" event. And also you must do some error in that case. For eg.
<img src="someFakeSrc" onerror='javascript:eval(window.alert("sometext"))'>
HTML doesn't see a src of picture then run a 'onerror' event.
Open JavaScript:- this code isn't editable as it is locked by the Host! So also I can't add any selector inside it!
But I can add another code outside of it. Like:- <ex ex="ex">Open JavaScript</ex>
So, I want to create a <script src="/javascript.js"></script> by fetching the URL from Open JavaScript.
They also didn't allow PHP there, otherwise I could do it myself. There is only one way to do it via JavaScript.
And I don't want to add the script inside <head> tags! It should be in the footer (<div class="body-footer"> Here </div>). There are not only one JavaScript link in the page, there are so many JavaScript links. So also I can't use $("a[href$='.js']");. Its became more tougher for me.
So how can I do this using JavaScript or jQuery?
Here is my implementation, where <script> tag is added before <a> with value of href.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
var hrefValue = $("div#test a").attr("href");
$("div#test a").before("<script src='"+hrefValue+"'><\/script>");
console.log($("#test").html());
});
});
</script>
</style>
</head>
<body>
<div id="test">
Open JavaScript
</div>
</br></br>
<button>CLICK it, to add href value of anchor tag to newly created sibling element</button>
</body>
</html>
Is it possible to create your own text contents (text between the HTML tags) of my custom HTML tags?
I used this code:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<script>
$(document).ready(function () {
$("eg").replaceWith("<h2>Put the text content of eg here</h2>");
});
</script>
</head>
<body>
<eg>My text</eg>
</body>
</html>
Between the <h2> tags (don’t think I should only use <h2> tags without JS) in my JavaScript code, any text can be placed that I like to have.
Example: <eg>I can type any text here but it’ll be still in h2 tag settings</eg>.
What should I write between <eg></eg> in JS to have any <h2> text content that will be written in my HTML code?
If you want to replace the <eg>Test</eg> with <h2>Test</h2> then you can just do this: $("eg").replaceWith("<h2>" + $("eg").html() + "</h2>");.
Here is an example: http://plnkr.co/edit/urd69pJSXQngGIsYYSjq
If I'm understanding correctly, you just want to append an element to the DOM, so you can just use the html method as follows:
$("eg").html("<h2>Any text can be placed here</h2>");
Have a look at the docs if you need more info.
Note: You closed but didn't open your body tag.
Replace:
</body>
With something like:
<body> <eg> Your custom content is between body tags now </eg> </body>
And you also have two HTML tags, remove the second
<html>
No. It wouldn't be HTML anymore.
However, if you wrote xHTML (which is a form of XML), then you could extend the DOM with your own elements. But that would be XML, not HTML.
And if you tried adding custom elements to a page, browsers wouldn't know what to do with them. Even if some browsers might display them, it's a very bad idea. Use a class name instead.
Creating and using custom tags is a bad idea. It should be avoided.
You are probably looking for this:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<script>
$(document).ready(function () {
$("#my_h2").html("<h2>Any text can be placed here</h2>");
});
</script>
</head>
<h2 id="my_h2"></h2>
</body>
</html>
For more, read-up on CSS selectors. (They are the same as jQuery selectors.)
Hope this helps.
I'm learning Javascript, and I'm trying to change the text of an 'id' when the user clicks a button. Here's the code:
<!DOCTYPE html>
<html>
<body>
<p id="demo">Hello</p>
<button type="button" onclick="document.getElementById("demo").innerHTML = "Hey There"">Try it</button>
</body>
</html>
When I select the button, nothing happens. What am I doing wrong, and how can I fix it?
My answer will possibly look complicated at first, but I do believe that starting with a good conception is healthy and will make things more enjoyable. A common problem with learning tools actually is that they promote themselves as "QUICK" ways of learning something. There is some good you can get from them, but there is some caveats. It can be harder to learn if you skip too many steps.
HTML is by design used to describe the presentation of the page, while JavaScript is by design used to interact with that page.
Inline JavaScript is a bad practice and will often lead to issues like the one you're facing. Inline here means that you directly put interactive code inside the HTML presentation. If you do that, you will quickly find that this part of HTML becomes messy. Then, it will look hard to deal visually with delimiters since there is >, " and ' all at the same place.
Another problem with inline javascript is that it mixes two concepts: interaction and presentation. HTML should be only used for presentation.
In that way, you could edit your code to make it look like this:
HTML
<!DOCTYPE html>
<html>
<body>
<p id="demo">Hello</p>
<button id="btn" type="button">Try it</button>
<script>
document.getElementById('btn').onclick = function() {
document.getElementById('demo').innerHTML = 'Hey There';
}
</script>
</body>
</html>
What it does is when the document loads, it will interactively associate an action to your button if JavaScript is enabled in the user's browser. If it's not, the page won't fail at all, it will be downgraded. In that sample, the presentation (html) is totally separated from the interaction (script). As a bonus, there is no more f*cks with double or single quotes.
For the script part, I personnally like to work it a little bit more so it is easier to use and read.
Something like this:
JavaScript
_e('btn').onclick = function() {
_e('demo').innerHTML = 'Hey There';
}
function _e(id) {
return document.getElementById(id);
}
Or even better:
JavaScript
_e('btn').addEventListener('click', function() {
_e('demo').innerHTML = 'Hey There';
}, false);
function _e(id) {
return document.getElementById(id);
}
The last version will explicitly state your intention to do something when you click on your button. This actually makes it really clear what you intend to do with your button.
I hope this helps and good luck :)
-You are using double quote inside double quote. So it results in breaking of string like this.
onclick="document.getElementById(" its the first string and so on...
-Either you can use single quote inside double quote or double quote inside single quote.
here is the working code:
First Approach(Using single quote inside double quote):
<!DOCTYPE html>
<html>
<body>
<p id="demo">Hello</p>
<button type="button" onclick="document.getElementById('demo').innerHTML = 'Hey There'">Try it</button>
</body>
</html>
Second Approach(Using double quote inside single quote):
<!DOCTYPE html>
<html>
<body>
<p id="demo">Hello</p>
<button type="button" onclick='document.getElementById("demo").innerHTML = "Hey There"'>Try it</button>
</body>
</html>
More about single and double quotes Read this
The problem is that you are breaking the string because of the quotes:
<!DOCTYPE html>
<html>
<body>
<p id="demo">Hello</p>
<button type="button" onclick="document.getElementById('demo').innerHTML = 'Hey There'">Try it</button>
</body>
</html>
notice I changed the double quotes to single quotes
It's always better to have JavaScript execute in a separate function. Instead of inlining JS in the onclick attribute, try this approach:
<!DOCTYPE html>
<html>
<body>
<p id="demo">Hello</p>
<button type="button" onclick="textChange()">Try it</button>
<script>
var textChange = function( ) {
document.getElementById("demo").innerHTML = "Hey There";
};
</script>
</body>
</html>
That way, on top of the fact that your code is easier to read, you will avoid the double quote/single quote issue you had.