How to change from onclick to onload? - javascript

I'm using this for the preview of a saved HTML code (also live)
But for the 1st time I have to click and enter to view the preview
How can I see preview once the browser window opens?
Code:
function showHTML () {
textarea1 = document.getElementById('htmltxt');
viewHtml = document.getElementById('htmlpreview');
viewHtml.innerHTML = textarea1.value ;
}

As far as I have understood the requirement is to call showHTML() on page load..
<body onload="showHTML()">
<textarea id="htmltxt">
aksjdhkasjdhakjds
</textarea>
<span id="htmlpreview"></span>
<script>
function showHTML() {
textarea1 = document.getElementById('htmltxt');
viewHtml = document.getElementById('htmlpreview');
viewHtml.innerHTML = textarea1.value;
}
</script>
</body>

Simply call your function when the document loads, as well as in your click handler:
function showHTML() {
textarea1 = document.getElementById('htmltxt');
viewHtml = document.getElementById('htmlpreview');
viewHtml.innerHTML = textarea1.value;
}
document.addEventListener('DOMContentLoaded', showHTML)
Note that instead of attaching a DOMContentLoaded listener, you could just call showHTML() somewhere inside a <script> tag that sits after both your #htmltxt textarea and your #htmlpreview element (so that they will have been parsed before execution begins).

Related

New window size

I know that this question is been asked tons of times, but I'm asking not exactly that. This code belongs to website menu bar, so I have to keep this code, otherwise design would be totally different.
Code:
<li class="removable-parent">
<a class="removable-parent" href="http://88.88.209.56:12/player.html" data-
link-type="EXTERNAL" target= "_blank">
<span id="4884dd90" class="preview-element Link item-link magic-circle-
holder text-element custom" data-menu-name="PREVIEW_LINK" >Spiller</span>
</a>
<script>
function clickHandler() {
window.open(this.href, "_blank", "width=640,height=480");
return false; // to prevent default action.
} document.getElementById("http://88.88.209.56:12/player.html").onclick=clickHandler
}
</script>
</li>
So how can I make that this code opens window in decided size?
You will need to use javascript.
Get a reference to your object and handle the click event. In that event, use window.open with the proper parameters to set the width and height of your pop-up window.
Make sure you cancel the original event so you don't end up with two pop-ups.
Something like:
<script>
function clickHandler() {
window.open(this.href, "_blank", "width=640,height=480");
return false; // to prevent default action.
}
var elems = document.querySelectorAll(".removable-parent");
for (var i = 0, elem; elem = elems[i]; ++i) {
elem.onclick = clickHandler;
}
</script>
Or, if you wish to apply this behavior on one link, first add an id attribute to your link:
<a class="removable-parent" id="myelement" href="http://88.88.209.56:12/player.html" data-link-type="EXTERNAL" target= "_blank">
The script should then be simplified so it applies only on that element:
<script>
function clickHandler() {
window.open(this.href, "_blank", "width=640,height=480");
return false; // to prevent default action.
}
document.getElementById("myelement").onclick = clickHandler;
</script>

Why is the button disapearing?

The text "Now I'm here..." is supposed to disappear when the button is clicked, not the button itself.
<div id="alpha">Now I'm here...</div>
<button type="button" onclick="remove()">Remove</button>
<script>
function remove()
{
var element = document.getElementById("alpha");
element.parentNode.removeChild(element);
}
/*function add()
{
var ele = document.createElement("p");
var text = document.createTextNode("This is new text");
ele.appendChild(text);
var location = document.getElementById("alpha");
location.appendChild(ele);
}*/
</script>
There is another function called remove that is interfering with your function.
Rename your function and it works fine:
http://jsfiddle.net/fL3gZ/
<div id="alpha">Now I'm here...</div>
<button type="button" onclick="Myremove()">Remove</button>
<script>
function Myremove()
{
var element = document.getElementById("alpha");
element.parentNode.removeChild(element);
}
</script>
What's happening is remove() is being called on the button itself! HTMLElement.prototype.remove is an existing function (in some browsers)! Oh god!
var button = document.getElementsByTagName("button")[0];
// surprise! this is what's actually happening
button.remove();
Check out this alternative approach. See: fiddle
Change HTML to
<div id="alpha">Now I'm here...</div>
<button type="button">Remove</button>
Then use this JavaScript
function remove(id) {
var elem = document.getElementById(id);
if (elem) elem.parentNode.removeChild(elem);
}
var button = document.getElementsByTagName("button")[0];
button.addEventListener("click", function(event) {
remove("alpha");
event.preventDefault();
});
A couple things about this:
I'm favoring a more unobtrusive approach
The remove function is single purpose, and reusable
It will work in more browsers
You won't run into WTFs like you just experienced
remove() is already an excisting javascript method, so you are actually calling that method on your button instead of calling the function.
Just rename the function and it will be fine.
Fiddle: http://jsfiddle.net/WkUqT/7/
function removeText()
{
var element = document.getElementById("alpha");
element.parentNode.removeChild(element);
}
You are probably using chrome as your browser to test that code. Elements in chrome have a self-removal, .remove() method which removes the element itself from its container.
This is the main reason why the code above removes the button, because of this the appended event in your onclick() declaration was not invoked because the element invoking the event does not exist anymore. Try changing the name of your function to removeElement().

JavaScript focus() function doesn't focus textarea on page load

I have the following code.
<!DOCTYPE html>
<html>
<head>
<title>Focus issue</title>
<script type='text/javascript'>//<![CDATA[
window.onload=function(){
var text = document.getElementById('text')
window.onload = function() {
text.focus()
}
window.onhashchange = function() {
text.focus()
}
}//]]>
</script>
</head>
<body>
<textarea id="text"></textarea>
<p>Click to focus</p>
</body>
</html>
Here is a JSFiddle demo of the above code: http://jsfiddle.net/DvU63/
Why doesn't the focus go on the textarea box when the page loads? On clicking the link, the focus does go on the textarea box, but I also want the focus to go to the textarea box on page load. Why doesn't it happen?
Note: I am aware of the HTML5 autofocus attribute for textarea. But this question is about why the above JavaScript code does not do what I intend to do.
You're doing the .focus() statement from inside an onload handler that is itself defined inside an onload handler. This inner onload will not be called because by the time you define it the onload event will have occurred. Try this:
window.onload=function(){
var text = document.getElementById('text')
text.focus()
window.onhashchange = function() {
text.focus()
}
}
Your demo, updated: http://jsfiddle.net/DvU63/2/
do this
<script type='text/javascript'>
window.onload=function(){
var text = document.getElementById('text')
text.focus();
window.onhashchange = function() {
text.focus();
}
}
</script>
fiddle

Override javascript click event one time

I would like to replace the default action of an click event for all anchors in a webpage.
When I use this piece of code:
<html> <head> <script>
var list=document.getElementsByTagName("a");
var isChecked = false;
function load () {
for (i=0; i<list.length; i++)
{
var old = (list[i].onclick) ? list[i].onclick : function () {};
list[i].onclick = function () {
if( !isChecked)
{
test();
old();
}
else
old();
};
}
}
function test() {
alert("new action");
isChecked = true;
}
</script> </head>
<body onload="load();">
<a id="nr_1" onClick="alert('test');"> Anchor 1 </A>
<a id="nr_2" onClick="alert('test2');"> Anchor 2 </A>
</body> </html>
When I click an anchor I get the alert out of the test function and then the default function of the second anchor (even when I click the first anchor). When I then again click one of the two anchors I always get the Alert from the second anchor.
How do I put the original onclick functions back for each anchor element? When someone has an solution in jquery I would be glad as well.
EDIT
I was succesfull using this code:
function load()
{
$('a').attr('disabled', 'disabled');
$('a').click(function(e){
if($(this).attr('disabled'))
{
alert("new");
e.preventDefault();
$('a').removeAttr("disabled");
this.click();
}
});
}
On loading of the page this function is called giving all anchor elements a "disabled" attribute. After clicking the element the e.preventDefault() function disables the inline onclick function. Then I remove the "disabled" attribute and call the click function of the element again. because now the element doesn't have a "disabled" attribute only the default function is performed. I'm still open for "more elegant" solutions to this problem, but for now I'm a happy camper!
If you use jQuery you can combine a one-time handler with a persistent handler:
Documentation for .one() and .on()
Working Example: http://jsfiddle.net/Q8gmN/
Sample HTML:
<input type="button" id="click" value="click" />
​
Sample JavaScript:
button.one('click', function () {
console.log('one time function fired');
});
button.on('click', function () {
console.log('persistent function fired');
});
​

Why does positioning of <script> in HTML for window.onload event matters?

I have a form that hides a text input field dynamically, depending on the initial choice of an option field upon loading. After some trial and error, I realise that the <script> tag has to be placed below the <form> elements in order for this functionality to work:
<html>
....
<body>
....
<form>
<select name=choice>
<option value=0 selected>Default</option>
<option value=1>Others</option>
</select>
<input type=text name=others></input>
</form>
....
<script type='text/javascript'>
function init()
{
var A = document.forms[0].choice;
var B = document.forms[0].others;
if(A.options[A.selectedIndex].value == 0) B.style.display = 'none';
}
window.onload = init();
</script>
....
</body>
</html>
The event window.onload is a global event that is triggered after all resources of the page including DOM, images, frames, etc have loaded. Then, why is it still necessary for the <script> tag to be placed below the <form> elements?
Because your executing the init function instead assigning the pointer to the function...
Change:
window.onload = init();
To:
window.onload = init;
It's because of a typo in your code:
window.onload = init();
This is actually calling the init function immediately (and then setting window.onload to undefined). Try:
window.onload = init;
JavaScript and HTML works correctly. But I see some miss understand on your code.
window.onload = init();
This line means use execute init function immediately and set function result as onload event. That is the reason why it works when you place it under form element.

Categories

Resources