Javascript doesn't seems to be running - javascript

Ok, I have been trying to make it work past 30 minutes.
Everything works fine in this jsfiddle :- http://jsfiddle.net/6KT4R/1/
But when I run this on my local wamp server..nothing seems to happen!.
Code :-
<script src="js/jquery-1.8.2.min.js" type="text/javascript">
</script>
<script type="text/javascript">
var inputLtc = document.getElementById('input-ltc'),
inputBtc = document.getElementById('input-btc');
var constantNumber = 0.022632;
inputLtc.onkeyup = function () {
var result = parseFloat(inputLtc.value) * constantNumber;
inputBtc.value = !isNaN(result) ? result : '';
};
</script>
<input type="text" name="ltc" id="input-ltc">
<input type="text" name="btc" id="input-btc" readonly>
What is possibly wrong here?
Thanks.

The script is executing before the DOM is loaded. Try:
window.onload = function(){
var inputLtc = document.getElementById('input-ltc'),
inputBtc = document.getElementById('input-btc');
var constantNumber = 0.022632;
inputLtc.onkeyup = function () {
var result = parseFloat(inputLtc.value) * constantNumber;
inputBtc.value = !isNaN(result) ? result : '';
};
}
As m59 suggested there is an improved method of executing the event onload. The following code snippet is preferred:
var funct = function(){
var inputLtc = document.getElementById('input-ltc'),
inputBtc = document.getElementById('input-btc');
var constantNumber = 0.022632;
inputLtc.onkeyup = function () {
var result = parseFloat(inputLtc.value) * constantNumber;
inputBtc.value = !isNaN(result) ? result : '';
};
}
if (window.attachEvent){
window.attachEvent('onload', funct);
}else{
element.addEventListener('load', funct, false);
}

You're getting your element references before the elements exist on the page. In the jsfiddle, the javascript is executed after the html. You could reproduce this by moving your script tag below the related html. It is best practice to put all script tags just before the end of the body like this:
<script></script>
</body>
Otherwise, you'll need to register an event listener to watch for page load and execute your javascript code then.
window.addEventListener('load', function() {
console.log('loaded!');
});
with jQuery:
$(document).ready(function() {
console.log('loaded!');
});
//this is the jQuery shorthand for the same function above
$(function() {
console.log( "loaded!" );
});

Related

Javascript fires twice Wordpress admin metabox

I added a inline Javascript code to my metabox callback function.
add_action( 'add_meta_boxes', function() {
add_meta_box( 'catalog-item', 'Gegevens', 'catalog_details_callback', 'catalog', 'advanced' );
});
function catalog_details_callback( $post ) {
<input type="text" class="price" name="price" id="price"/>
<script type="text/javascript">
document.getElementById('price').onfocusout = function() {
var regex = /^(\d+[,]+\d{2})$/;
if (regex.test(this.value) == false ) {
this.value = this.value.replace(/([^(\d|,)]|,{2})/g, "");
}
var before = this.value.replace(",", ".");
var roundoff = parseFloat(before).toFixed(2);
var after = roundoff.replace(".", ",");
alert(after);
}
</script>
}
If the function is triggered the function fires the alert twice.
Does anybody know how I fix this?
There could be multiple reason for this:
Please check if you have multiple event listeners. If so, try to check your condition. understand about event listeners here: https://developer.mozilla.org/en-US/docs/Web/API/Element/focusout_event
onfocusout bubbles, means if you have any event written on parent as well as child then both gets called. try to add
document.getElementById('price').onfocusout = function(event) {
event.preventDefault();
event.stopPropagation();
var regex = /^(\d+[,]+\d{2})$/;
if (regex.test(this.value) == false ) {
this.value = this.value.replace(/([^(\d|,)]|,{2})/g, "");
}
var before = this.value.replace(",", ".");
var roundoff = parseFloat(before).toFixed(2);
var after = roundoff.replace(".", ",");
alert(after);
}
If still issue persists then try to add the debugger in the function can check the call trace in google developers console.
I had the same issue with Wordpress.
This works for me
const price_field = document.getElementById('price');
price_field.addEventListener('focusout', (event) => {
var regex = /^(\d+[,]+\d{2})$/;
if (regex.test(price_field.value) == false ) {
this.value = price_field.value.replace(/([^(\d|,)]|,{2})/g, "");
}
var before = price_field.value.replace(",", ".");
var roundoff = parseFloat(before).toFixed(2);
var after = roundoff.replace(".", ",");
price_field.value = after;
alert(after);
});

How can I access this library functions?

Just started learning JS, and been having an issue with a library i'm trying to import.
The developer recommends the following:
<script>
window.sodium = {
onload: function (sodium) {
let h = sodium.crypto_generichash(64, sodium.from_string('test'));
console.log(sodium.to_hex(h));
}
};
</script>
<script src="sodium.js" async></script>
However, this only executes when the page loads - I can't run the functions further down the page when they are required. As such:
<script>
var App = new function(myLibrary){
this.sodium = myLibrary;
this.example = function () {
h = this.sodium.crypto_generichash(64, this.sodium.from_string('test'));
return this.sodium.to_hex(h);
}
}
var create = new App(window.sodium);
</script>
/...../
<script>console.log(create.example());</script>
<script src="sodium.js" async></script>
How would I do this? I kept getting errors such as "sodium.crypto_generichash" is not a function. Or sodium is not defined.
This code is running before the library is loaded:
<script>
var App = new function(myLibrary){
this.sodium = myLibrary;
this.example = function () {
h = this.sodium.crypto_generichash(64,
this.sodium.from_string('test'));
return this.sodium.to_hex(h);
}
}
Try removing the async and change the order of the scripts.
And run your code inside a window.onload function:
window.onload = function() {
//your code
}

How I can call ext.net button from Javascript and set to enable it?

var btnNextp = Ext.getCmp('<% = btnNextPage.ClientID %>').getEl().dom.id;
//var btnNextp = document.getElementById('<% = btnNextPage.ClientID %>');
// $("#btnNextPage").attr({ disabled: "false" });
Ext.getCmp('btnNextp').setBtnDisable(false); //not works properly
// Ext.getCmp('btnNextPage').enable(); //not works properly
These examples also creates uncaught errors in javascript.But why ?where is the problems.
Thanks in advance.
Try this:
<script type="text/javascript">
var EnableButton = function () {
var btnNextp = #{btnNextPage};
btnNextp.setDisabled(false);
};
</script>

Replace All Words In Document Body Doesn't Work

Firstly sorry for my english, i have code that doesnt work when I execute it on
<script language="javascript" src="/thecode.js"></script>
I put thecode.js on footer
var msg=document.body.innerHTML;
for(var i=0;i<msg.length;i++){
var tx=document.body[i].innerHTML;
tx=tx.replace(/dog/ig,'animal');
tx=tx.replace(/apple/ig,'fruit');
tx=tx.replace(/\[VIdEo\]/ig,'Video');
tx=tx.replace(/http\:\/\/example\.com/ig,'http://thelink.com');
document.body.innerHTML=tx;}
I think i dont make any fault, but when i execute it, its doesnt work.
thank for your attention... :)
no need to iterate body element
try this:
want to change to with that js? i have used to make it
function addTitleToSurveyUrls() {
var elements = document.getElementsByTagName('a');
for(var el in elements) {
var element = elements[el];
var href = element.getAttribute("href");
if(href.indexOf('survey_')>-1) {
element.setAttribute('title', 'Some TITLE HERE');
}
}
}
function replaceBodyElements() {
var tx=document.body.innerHTML;
tx = tx.replace(/dog/ig,'animal');
tx = tx.replace(/apple/ig,'fruit');
tx = tx.replace(/\[VIdEo\]/ig,'Video');
tx = tx.replace(/http\:\/\/example\.com/ig,'http://thelink.com');
document.body.innerHTML=tx;
}
window.onload = function(){
replaceBodyElements();
addTitleToSurveyUrls();
// ... some another operations
};
also
document.onreadystatechange = function () {
var state = document.readyState;
if(state == 'complete') {
replaceBodyElements();
addTitleToSurveyUrls();
}
}​
I've used onload event because maybe document has dynamic elements and etc. so better wait while all elements get loaded and change it.
or You can replace window.onload with window.document.onload

processing.js change script source

I need to find a way where I can dynamically change the source of a processing script inside an HTML document.
This is the embedded script which works fine:
<script type='application/processing' src='sketch.txt' id="applet">
</script>
Now I try to change the source:
$('#applet').attr('src', 'sketch2.txt');
alert($('#applet').attr('src'));
The alert shows that the source was changed to 'sketch2.txt' but the applet still remains the same. I think I need to refresh the script in some way.
Thank you in advance for any help!
I believe you have to manually attach each proc to the canvas, instead of just changing the the source file. This worked here:
function first_call(processing) {
processing.size(300,300);
processing.background(100);
var called = false;
processing.draw = function() {
if (!called) { processing.println("called #1"); called = true; }
}
}
function second_call(processing) {
processing.size(400,400);
processing.background(200);
var called = false;
processing.draw = function() {
if (!called) { processing.println("called #2"); called = true; }
}
}
var canvas = document.getElementById('canvas1');
var processingInstance = new Processing(canvas, first_call);
var processingInstance = new Processing(canvas, second_call);

Categories