html input onload does not work [duplicate] - javascript

Is it possible to trigger a Javascript script, when an input element or any other html element is rendered. This script should be triggered from within the html tag, so that we should be able to pass 'this' to the js function.

No, there is no such event.
However, a <script> tag placed directly after the HTML element would have a similar effect: It would be executed directly after the element has been rendered:
<input type="text" id="input123" value="Hello World!">
<script>
alert("Input123 is now ready:"+document.getElementById("input123").value);
</script>
In most cases, however, it is best to use the document-wide load (or DOMReady, or jQuery's .ready()) to start any script operations. The DOM will be fully ready then.

A way to simulate such an event is to create a custom data-* atttribute (HTML-5 valid) and use that as a selector. Then in the main javascript code, you can add a selector for anything which has this specific data-XXX attribute and evaluate the javascript code inside.
Example HTML code:
<div data-onload="sampleFunction('param1', 2)"></div>
Example Javascript code (using jQuery). It is also possible to use normal DOM to find elements with this attribute.
/* Find any element which has a 'data-onload' function and load that to simulate an onload. */
$('[data-onload]').each(function(){
eval($(this).data('onload'));
});
This works well. I actually use it in production.

No. However, any script placed after the markup of the input element, will be run with the input element available because it is parsed before the script. So, if this was all in the body:
<input id="a">
<script>document.getElementById('a');</script>
That would all work anyway.

I have an input element that gets dynamically added to the document and needs to get initialized.
It's not perfect, but here's a way to initialize the widget the first time the input is used:
<input onfocus="initwidget(this)">

There is a trick. There are onload and onerror events for inputs have type="image" src="..." attributes. You can use onerror by passing empty or always wrong to src and change the type to proper one when onerror event triggred:
function func(input) {
console.log("Input loaded");
input.type = "text";
input.value = "Worked!";
input.removeAttribute("src");
// ...
}
<input type="image" value="" onerror="func(this)" src=""/>

No this is not possible. You could however use jQuery + $(document).ready(function) to modify any input field you want right after the page has finished loading.

No, there is not. Just run your code from the document "ready" handler, or use something like jQuery to give you a way to run code at "ready" (which is when the DOM is complete but images may not have loaded).

Related

jQuery: Modifying A tags within a textarea

I want to add target="_blank" to some "A" tags within a textarea. I am able to modify them when they are not inside a textarea but I cannot do it when they are inside the textarea.
For this code I only want to add the target attributes when it is an external link. jsFiddle link
<form>
<textarea id="description">
internal
external no target
external target
external no target
internal
external no target
</textarea>
<button class="btn btn-success">Go</button>
</form>
external no target
I have tried a few different ways of specifying that the links are within a textarea but none work. Here is one version I have tried...
// This does not work...
$('#description a:not([target])').not('a[href*=website]').attr('target', '_blank');
// This works for the link
$('a:not([target])').not('a[href*=website]').attr('target', '_blank');
Any help much appreciated. Thanks.
Since they are text and not actual elements you need to manipulate the string.
A simple way is to put the string into a temporary element as html , run dom methods on that element and return the updated html
Something like:
$('#description').val(function(_,currVal){
var $div = $('<div>').append(currVal);
$div.find('a:not([target])').not('a[href*=website]').attr('target', '_blank');
return $div.html()
})
Anything you put inside a <textarea> tag becomes its value in plain text.
That means they are no longer HTML elements and thus cannot be selected with jQuery.
Textareas are used for user input, and the only reason to put anything inside them is as a default value.
Why do you want to have links inside it?

jQuery click event does not fire on 'loaded' html

I'm trying to understand why loading HTML into a div block renders its class statement effectively non-existent to a click event.
My HTML code looks like this:
<div id="load-to"></div>
<div id="load-from">
<div class="load-from-css"> Hello!</div>
</div>
<button>load it!</button>
My JS code looks like this:
$('button').click(function(){
var html = $('#load-from').html();
$('#load-to').html(html);
});
$('.load-from-css').click(function(){
alert('clicked');
});
When I click the button the HTML from the lower div block is loaded into the upper div block, and then the HTML looks like this:
<div id="load-to">
<div class="load-from-css"> Hello!</div>
</div>
<div id="load-from">
<div class="load-from-css"> Hello!</div>
</div>
My question is, why does the second click event (defined in my jQuery code) only work on the original lower "Hello!" div block but not on the loaded upper one, when both have the same class definition?
Other answers have already covered the core reason for your problem (that copying the HTML of an element and placing it elsewhere will create a brand new DOM element and does not copy any events that were bound to the original element... keeping in mind that when you add an event listener, it will only bind to any elements that exist at the time that you do so)
However, I wanted to add some other options for accomplishing what you want to do.
jQuery has a few different techniques that make this sort of thing easy:
.clone() will essentially do the same thing as you are doing now*, it will copy the HTML content and create a new DOM element. However, if you pass true (ie: .clone(true)), it will clone it with all data and events intact.
* note that to truly get the same result as using .html(), you need to do .children().clone(), otherwise you'll get both the inner and outer div.. this may or may not be necessary depending on the use case
ex: https://jsfiddle.net/Lx0973gc/1/
Additionally, if you were in this same situation but did not want to make a clone, and simply wanted to move an element from one place to another, there is another method called .detach() which will remove the element from the DOM, but keep all data and events, allowing you to re-insert it later, in the same state.
ex: https://jsfiddle.net/Lx0973gc/2/ (not the best example because you won't see it move anywhere, but it's doing it!)
As another alternative, you can use delegated event binding, which actually binds the event to a different element (a parent) which you know won't change, but still allows you to target a child element within it:
$('body').on({
'click': function() {
alert('clicked');
}
}, '.load-from-css');
ex: https://jsfiddle.net/Lx0973gc/4/
The $('.load-from-css') finds all elements currently existing and .click(...) attaches a listener to all these elements. This is executed once.
Then you copy the raw html which does not transfer any listeners. The DOM has nodes onto which the listeners are attached but when you copy the plain HTML you essentially create new nodes based on the html.
Because you are copying just the HTML. The js file is loaded at the beginning, when there is just one instance of a div with the "load-from-css" class. You should execute again the code adding the listener after you copy the html. Somethinglike:
$('button').click(function(){
var html = $('#load-from').html();
$('#load-to').html(html);
$('.load-from-css').click(function(){
alert('clicked');
});
});
#load-to inner HTML is initially empty. so added click listener only for #load-from .load-from-css. Dynamically bind element will not attach the click listener.
jQuery new version have the feature to attach the event for dynamic elements also. Try this
$('button').click(function(){
var html = $('#load-from').html();
$('#load-to').html(html);
});
$(document).on('click', '.load-from-css', function(){
alert('clicked');
});
Also we can use like this
$( document ).delegate( "load-from-css", "click", function() {
alert( "Clicked!" ); // jQuery 1.4.3+
});
Simply because the page did not refresh. You loaded a content to another content without loading the page, and the browser wont recognized any event added to the loaded element.
What you should do is load your javascript tag with the load along with the content.
Your code should be like this:
<div id="load-to">
<div class="load-from-css"> Hello!</div>
</div>
<div id="load-from">
<div class="load-from-css"> Hello!</div>
<script>$('button').click(function(){
var html = $('#load-from').html();
$('#load-to').html(html);
});
$('.load-from-css').click(function(){
alert('clicked');
});</script>
</div>

Calling a javascript function on element load

So I am working with a ckEditor implementation in my project, and I want to provide autocomplete functionality for one of its dialog boxes. I implement the autocomplete functionality by calling a javascript function on a specific input field. However, I am not completely sure on how to obtain the specific input element, as it only appears after I hit a button in ckeditor, so it is no obtainable on document load.
Is there anyway to fire a javascript function upon the loading of a specific div/element? I am trying to use Jquery's $().load function, but it does not seem to be firing. Here is a short example
$(".cke_reset_all cke_1 cke_editor_documentBody_dialog").on("load",function(){
console.log("Successful firing")
//some code here
});
I am not seeing any text in my console, but div with that class name is appearing.
Everytime the dialog box containing the input loads , the following div is created
<div class="cke_reset_all cke_1 cke_editor_documentBody_dialog " lang="en" aria-labelledby="cke_dialog_title_113" role="dialog" dir="ltr">
so I am trying to run my autoComplete script after the loading on this div is done, as the input field I want is nested within it. Any ideas?
The load method in jQuery is an AJAX shorthand method, so it's not what you're after here.
If you want to bind to the load event, you need to use the on method (or bind in earlier versions of jQuery).
Details here: http://api.jquery.com/on/
The load event only applies to some elements, like body, iframe, img, input, script.
In your case, to detect if the input element is present in the page you'll probably have to rely on polling with a setTimeout or setInterval loop. Within the loop, the code will look like:
var inputs=$("div.cke_editor_documentBody_dialog input");
if (inputs.length==1) // do something
Note that the way you wrote the selector in your question is incorrect.
Bind the On method to the parent div, then look for the id/class and carry out your logic/call a function.
$(function () {
$('#parentDiv').on('click' ,'yourselectorhere', function() {
console.log('working');
});
});

Access jQuery function from page elements generated in jQuery

I have a little jQuery call that returns perfectly for my element bound to an on function:
$(".claim-detail a").on("click", function(){
...some stuff
})
Then a little html:
<p class="claim-detail">get the data</p>
Works perfectly.
But I need that claim-detail html to be generated in javascript. And when I move it there, the html is generated on the page with no problem, but the jQuery function breaks entirely . Doesn't matter which piece precedes which in the javascript.
Anything I'm doing obviously wrong?
You need to use event delegation for dynamically generated elements that do not exist at DOM ready. Change your click handler to:
$(document).on("click", ".claim-detail a", function(){
Chances are (I'm saying this because we don't know how your code was generated) that your click handler was trying to bind to the element before it existed
Use
<p class="claim-detail"><a onclick="myNewFunction()" href="#modal" data-toggle="modal">get the data</a></p>
Where my myNewFunction is the function you were using in the event. Other option is create the event when you actually finish creating the HTML id and/or classes in the DOM.

Is there an onload event for input elements?

Is it possible to trigger a Javascript script, when an input element or any other html element is rendered. This script should be triggered from within the html tag, so that we should be able to pass 'this' to the js function.
No, there is no such event.
However, a <script> tag placed directly after the HTML element would have a similar effect: It would be executed directly after the element has been rendered:
<input type="text" id="input123" value="Hello World!">
<script>
alert("Input123 is now ready:"+document.getElementById("input123").value);
</script>
In most cases, however, it is best to use the document-wide load (or DOMReady, or jQuery's .ready()) to start any script operations. The DOM will be fully ready then.
A way to simulate such an event is to create a custom data-* atttribute (HTML-5 valid) and use that as a selector. Then in the main javascript code, you can add a selector for anything which has this specific data-XXX attribute and evaluate the javascript code inside.
Example HTML code:
<div data-onload="sampleFunction('param1', 2)"></div>
Example Javascript code (using jQuery). It is also possible to use normal DOM to find elements with this attribute.
/* Find any element which has a 'data-onload' function and load that to simulate an onload. */
$('[data-onload]').each(function(){
eval($(this).data('onload'));
});
This works well. I actually use it in production.
No. However, any script placed after the markup of the input element, will be run with the input element available because it is parsed before the script. So, if this was all in the body:
<input id="a">
<script>document.getElementById('a');</script>
That would all work anyway.
I have an input element that gets dynamically added to the document and needs to get initialized.
It's not perfect, but here's a way to initialize the widget the first time the input is used:
<input onfocus="initwidget(this)">
There is a trick. There are onload and onerror events for inputs have type="image" src="..." attributes. You can use onerror by passing empty or always wrong to src and change the type to proper one when onerror event triggred:
function func(input) {
console.log("Input loaded");
input.type = "text";
input.value = "Worked!";
input.removeAttribute("src");
// ...
}
<input type="image" value="" onerror="func(this)" src=""/>
No this is not possible. You could however use jQuery + $(document).ready(function) to modify any input field you want right after the page has finished loading.
No, there is not. Just run your code from the document "ready" handler, or use something like jQuery to give you a way to run code at "ready" (which is when the DOM is complete but images may not have loaded).

Categories

Resources