Reputation: 996
I'm using some software where it is possible to add some custom script. After some trial and error I found out that this script only work if I put it like this:
setTimeout(function(){
//code
}, 900);
But I find this a little bit ugly, and I feel like it should be possible to do it smarter. I also don't know if at other computers I may need longer time. Maybe for someone else I need to set it to 5000, and for some other one it is okay to have it at 300.
Is it possible to fire the function after everything is loaded ?
This method, I tried, but didn't work:
$(document).ready(function(){ .. });
document.addEventListener('DOMContentLoaded', function() {...}, false);
Here is my complete code:
setTimeout(function(){
function correct(searchString, replaceString) {
$("textarea").bind("keyup", function () {
var $input = $(this),text = $input.val();
var pos = $(this).prop("selectionStart");
if (new RegExp(searchString).test(text.substring(pos-searchString.length,pos)) == true) {
var newText = text.substring(0,pos-searchString.length) + replaceString + text.substring(pos);
$input.val(newText);
var newpos = pos - searchString.length + replaceString.length;
this.setSelectionRange(newpos,newpos);
}
});
}
correct("RR", "ℝ");
correct(">=","≥");
}, 900);
I have set this as a custom header in a discourse forum (discourse.org)
Upvotes: 3
Views: 7653
Reputation: 36511
Your best bet is going to be hooking into the window.onload
event:
// cross-browser event listener
function addEvent(evnt, elem, func) {
if (elem.addEventListener) // W3C DOM
elem.addEventListener(evnt,func,false);
else if (elem.attachEvent) { // IE DOM
elem.attachEvent("on"+evnt, func);
}
else { // No much to do
elem[evnt] = func;
}
}
// add the actual event
addEvent('load', window, function(){
// execute your code here
})
Upvotes: 1
Reputation: 4619
Execute on document ready.
function correct(searchString, replaceString) {
$("textarea").bind("keyup", function () {
var $input = $(this),text = $input.val();
var pos = $(this).prop("selectionStart");
if (new RegExp(searchString).test(text.substring(pos-searchString.length,pos)) == true) {
var newText = text.substring(0,pos-searchString.length) + replaceString + text.substring(pos);
$input.val(newText);
var newpos = pos - searchString.length + replaceString.length;
this.setSelectionRange(newpos,newpos);
}
});
}
$(document).ready(function() {
correct("RR", "ℝ");
correct(">=","≥");
});
Upvotes: 0