How to change the onload event of body after condition is met - javascript

I want to change the onload event of the body once a certain condition is met.
In my case the condition is that I first have to let the page load and get the current onload event and compare that to a certain string if it returns true I will then replace it with a different function to assign to the onload event.
Is this even possible since when the page loads my new onload event will practically do nothing so im guessing is that i have to change it before it reaches the body.
This was something I got from my previous question. I also added a few things:
$(document).ready(function(){
var x = new String(document.body.onload);
x = x.replace(/ /gi,"");
x = x.replace("functiononload(event){","");
x = x.replace("}","");
alert(x);
//what i want to do after i checked the old event if it is equal to something.
window.onload = function() {
newfunction();
x();
}();
});
<body onload="wewewe();">

Why don't you simply use :
$(document).ready(function() {
if (condition) {
// do something
}
else {
// do something other
}
});
body.onload and $(document).ready() are almost identical.

Related

How to use a variable after it was a jquery function has run

I realise similar questions have been asked before but still dont understand what is happening with my code. I want to access the variable seq outside of the jQuery function after the user has inputed their sequence into the textarea. The console.log inside the jquesry function returns the inputed sequence but the console.log outside of the jQuery function(where I eventually want to put some other code to analyse the sequence) runs before the jquery function and returns an empty string. How can I make the code that uses the var seq only run after the submit button is clicked? Thanks!
var seq = "";
$("#subSeqType").on("click", function() {
if ($("#proteinButton").is(":checked")) {
$("#newTextArea").append("<textarea name = 'sequence' rows = '10' cols = '80' placeholder = 'Enter Protein Sequence here' > < /textarea><br>");
}
if ($("#dnaButton").is(":checked")) {
$("#newTextArea").append("<textarea name = 'sequence' rows = '10' cols = '80' placeholder = 'Enter DNA Sequence here' > < /textarea><br>");
}
$("#subSeqType").remove();
$("#newTextArea").append("<input id = 'subSeq' type='Submit'>");
$("#subSeq").on("click", function() {
seq = $("textarea:input[name=sequence]").val();
console.log(seq);
});
});
console.log("The sequence " + seq);
Im gonna try to explain this but you should read a little about how a code works and runs.
Lets state to types of code statement:
Run time code
Run time code is every line of code that run when it is loaded by the browser
Run when call code
Run when call code is the code that will run after an event has occured.
Uniting this concepts:
When you create a listener, the rule that creates that listener is a run time code. But the code inside that listener will only run when called for.
I made a small example of this bellow, your problkem is not at changing the variable but when you are printing.
The printer button will print the var value
The cahnge calue will change that value one time
Hope this helps :)
let myVar = "before";
console.log(myVar);
function myFun(){
myVar = 'after';
}
function printer(){
console.log(myVar);
}
console.log(myVar);
<button onclick="myFun()">change value</button>
<button onclick="printer()">print</button>
You seem to using "click" event inside another "click" event.
An event action triggers and performs its operation and does not wait for another event inside or outside.
If you want variable value after certain operation of event, you need to assign it to variable and work when the event is triggered and operating.

Javascript - Multiple custom Event Listeners

I need to execute code from 3 different places on my website when an event gets triggered. I've added 3x listeners but for some reason only the first listener gets called.
Here's the code I'm testing at the moment: JSFiddle
window.addEventListener('tompina_event', function (e) {
document.write("triggered 1");
});
window.addEventListener('tompina_event', function (e) {
document.write("triggered 2");
});
window.addEventListener('tompina_event', function (e) {
document.write("triggered 3");
});
var evt = new CustomEvent('tompina_event');
window.dispatchEvent(evt);
Result:
triggered 1
This is the result I was hoping for:
triggered 1triggered 2triggered 3
It works, but the document.write destroys the original page and thus the execution of other code.
Please rewrite so the result is set in an other way like alert("triggered 1") or console.log("triggered 1").
The problem is with document.write(). Each call is overriding the strings from the previous call, and it appears that only one is firing. Change to console.log(), or document.body.innerHTML += "" and you will see them all firing.
The write() method is mostly used for testing: If it is used after an HTML document is fully loaded, it will delete all existing HTML.

Disabling window.ondeviceorientation after first iteration

I have an event handler that is executed only after a specific condition is met, as seen in the pseudo code below:
if(condition)
{
window.ondeviceorientation = function(e){
//my code
}
}
I only need this to run once to capture the gyroscope values and set some sessionStorage values.
How do I disable the ondeviceorientation loop after the first iteration? Here's what I'm currently doing, but not sure it's the best solution:
if(condition)
{
var stop_event_loop;
window.ondeviceorientation = function(e){
if(stop_event_loop) break;
//my code
stop_event_loop = true;
}
}
Simply clear out the event handler, like this:
if(condition)
{
window.ondeviceorientation = function(e){
//my code
window.ondeviceorientation = null;
};
}
Depending on your target browsers, I would recommend using the appropriate DOM-spec implementation for hitching functions to events, and then make sure you're stopping the handling of the event elsewhere.
So for the DOM 2 spec, you would use the EventTarget.addEventListener(); function to add something like:
window.addEventListener('deviceorientation', eventHandler, onCapture);
Then from within the event handler, you should check for and use the "e.preventDefault()" function to stop the code from executing if the "stop_event_loop" flag has been set to true, as well as return false to handle browser-specific implementations of event propagation.
Although, keep in mind that the scope of that "stop_event_loop" variable means it will be instantiated every time you step into that conditional block of code, so it will always be false when that function is tied to the event. If that's a close approximation to your current implementation, that's probably why your code is triggered every time the event is fired. You need to move that variable declaration somewhere where it will be a bit more permanent. I recommend NOT using the global scope, but anywhere outside of that conditional block should prevent it from being re-instantiated every time that function would trigger.
So your code would look like:
//elsewhere in your code
var stop_event_loop;
//your event loop
if(condition)
{
window.addEventListener('deviceorientation', eventHandler, onCapture);
var eventHandler = function (e) {
if (stop_event_loop) {
if (e.preventDefault) {
e.preventDefault();
}
return false;
} else {
//your code
}
}
}

Javascript onclick

I have code like
<a id='lnk1' onclick='do something' >test</a>
Later on code is added to the same anchor tag like
lnk = document.getElementById('lnk1')
lnk.onclick = function() { do something}
Now what is happening is that in the second piece of code the onclick function of the anchor tag is getting overwritten. What I want to happen instead is that the first onclick's code is run and after that the 2nd onclick's is run.
There is a very simple, standards-compliant way to do this:
lnk1.addEventListener('click', function() {
// do something
});
This doesn't work in IE before version 9, so you'll need to do this:
var handler = function() {
// do something
};
if ("addEventListener" in lnk1) { // standards-compliant browsers
lnk1.addEventListener('click', handler);
} else { // Internet Explorer < v9
lnk1.attachEvent('onclick', handler);
}
This will work, and both the original function specificed in the HTML attribute and in the code above will run. HOWEVER it would be far nicer to define all your event handlers in the same place: in the Javascript. Think hard about removing event handling logic from your HTML attributes.
You could try this:
var lnk = document.getElementById('lnk1'); // don't forget var!
var oldHandler = lnk.onclick;
lnk.onclick = function(ev) {
if (oldHandler) oldHandler(ev);
// do something ...
};
That code saves a reference to the old handler, and if it's not empty it calls it before doing whatever else the new handler wants to do.
You could put the call to the old handler after the new code, or mixed in, or whatever.
<a id='lnk1' onclick='do something' >test</a>
JavaScript
lnk1 = document.getElementById('lnk1')
lnk1.addEventListener('click',function() { do something}, false);
when setting onclick you are overwrite existing attribute, but assign click through event listener then it will be ok.
You have a mistake in your statement:
JAVASCRIPT
lnk = document.getElementById('lnk1')
lnk1.onclick = function() { do something} \\ replace lnk1 with lnk
lnk.onclick = function() { do something} \\ this will work
You have defined lnk as variable but your are calling lnk1 with onclick event. This is a wrong statement.
USE HTML
<a id='lnk1'>test</a>
See the Demo: http://jsfiddle.net/tm5cX/

Bind event to a div appearing

Can I create an event so I can execute some javascript whenever an element with a specific ID becomes visible or appears on the page?
The element comes from a remote resource (so isn't in MY html code but appears on page load) and I'd like some code to run when it appears (and only if it appears, it may not appear every load).
Thanks!
You can make a function that will check every X milliseconds if such element appeared on the page (a plain Javascript solution):
(​function ()​ {
var intervalId = window.setInterval(function() {
if (null != document.getElementById('myDivId')) {
// the div appeared on the page
// ... do your stuff here:
alert('its here!');
// optionally stop checking (obviously it's there already
// unless you decide to remove it)
window.clearInterval(intervalId);
};
}, 100); // perform check every 100 milliseconds
}​)()​;
There is the possibility that the DIV is there all the time, only not visible. So your checking function should be a little different:
var el = document.getElementById('myDivId');
if (null != el && (el.offsetWidth > 0 || el.offsetHeight > 0)) {
Basically (el.offsetWidth > 0 || el.offsetHeight > 0) indicates that element is not hidden by its or its parents' CSS properties.
If a selector doesn't find a match, it just won't run, so just having code like this is fine:
$("#elementID").each(function() {
//do something
});
Just run that statement in whatever code loads the ID, or alternatively rig it up in the ajax handler if that's how it's getting loaded like this:
$.ajaxSetup({
complete: function() {
$("#elementID").each(function() {
//do something
});
}
});
You could use live() method:
$('div_id_or_class').live('click', function(){
// ................
});

Categories

Resources