Javascript not being called after loading - javascript

I have a few javascript routines that I need to run with my application. When I run the application and go to view source, I see the javascript file import, and when I click on it, I am taken to the javascript file, so I know it is being brought down to the client. Right now, I have a simple alert in the beginning of the method I am calling, but that isn't even happening, so I'm not sure what's going on.
Does this look like the correct way to call the javascript when the button is clicked?
<p><input type="button" value="Add File" onclick="go();" /></p>
Here is the javascript file:
var typeAId= 0;
var typeBId= 0;
function addNewDocument(parentId, elementTag, elementId, html) {
// Adds an element to the document
var p = document.getElementById(parentId);
var newElement = document.createElement(elementTag);
newElement.setAttribute('id', elementId);
newElement.innerHTML = html;
p.appendChild(newElement);
}
function go(){
alert('ok');
}
function removeElement(elementId) {
// Removes an element from the document
var element = document.getElementById(elementId);
element.parentNode.removeChild(element);
}
function addNewDocument(input) {
var fileToRemove = 'file-';
alert('ok');
var elementName = null;
if(input === 'formAInput'){
elementName = 'formA[]';
typeAId++;
fileToRemove = fileToRemove+typeAId;
} else {
elementName = 'formB[]';
typeBId++;
fileToRemove = fileToRemove+typeBId;
}
var html = '<input type="file" name="'+elementName+'" /> ' +
'Remove';
if(input === 'formAInput'){}
addElement('typeAFilesDiv', 'p', 'file-' + typeAId, html);
} else {
addElement('typeBFilesDiv', 'p', 'file-' + typeBId, html);
}
alert('end');
}
Here is how I am importing the javascript:
<script src="/js/myJS.js"></script>
The js directory is located under the 'war' directory in my Google App Engine Project.
When I click the button, I do not see an alert.

Additional documentation, code, and screenshots would help the community answer more holistically. However, to answer your most basic question, yes, that is the correct way to use the onclick attribute.
I hypothesize that the JavaScript addFile function is not doing what you want it to or something is wrong with the document.ready event.

Related

Click event only works on second post

The below function works only after the page has been refreshed. When the page is refreshed again afterwards it stops working again and so on.
<button id="moreBtn" type="button" class="archive btn btn-default col-sm-12"></button>
function ShowHideBtn() {
var newss = 5;
var numItems = $(".news").length;
hidenews = "- Show Less Products";
shownews = "+ Show More Products";
$(".news:not(:lt(" + newss + "))").hide();
$("hr:not(:lt(" + newss + "))").hide();
if (numItems >= newss) {
$(".archive").show();
$(".archive").html(shownews);
$(".archive").on("click", function (e) {
e.preventDefault();
if ($(".news:eq(" + newss + ")").is(":hidden")) {
$("hr:hidden").show();
$(".news:hidden").show();
$(".archive").html( hidenews );
} else {
$("hr:not(:lt(" + newss + "))").hide();
$(".news:not(:lt(" + newss + "))").hide();
$(".archive").html(shownews);
}
return false;
});
} else {
$(".archive").hide();
}
}
Thanks in advance
This is a guess as there is insufficient information to confirm it. Please provide the full page HTML/code:
As browser page requests are stateless (so it can't know it is every other load), this sounds like a timing issue. The HTML would generally load slower the first time, so if the JS code is not positioned after the element it references (or is inside a DOM ready handler), then it may fail to find the .archive element. It is more likely random than "every other page load" though if it is a timing issue.
Try one of the following:
Place your JS code (or JS script include) after the element they reference. Just before the closing </body> tag is typical for this option.
Place your code inside a DOM ready handler, then its position does not matter. e.g. like:
$(document).ready(function(){
// Your code here
});
or the short-cut version of DOM ready:
$(function(){
// Your code here
});

How to use onhashchange with dynamic items

So, I have two select boxes on a webpage, but in different anchors (one on the page, the other in an iframe) and I'm trying to get the code to detect which anchor it's in, and then relay the selected value in that box to a link. Here's my code:
function locationHashChanged() {
if (location.hash === "#player") {
function setText(text) {
var selectVal = text;
var url = $('twitter').attr("href");
url = 'https://twitter.com/intent/tweet?button_hashtag=stream&text=Just enjoying ' + selectVal + ' on';
$('#twitter').attr("href", url);
}
}
if (location.hash === "#embeds") {
$(function () {
var $twitter = $('twitter');
$('#iframe').on('load', function () {
$(this).contents().find('#cds').change(function () {
var selectVal = $(this).val() || 'nothing much';
url = 'https://twitter.com/intent/tweet?button_hashtag=stream&text=Just enjoying ' + selectVal + ' on';
$('#twitter').attr("href", url);
}).change();
});
});
}
}
I know this is probably not right, or anywhere near right, but am I on the right track? I'm honestly a complete noob when it comes to javascript. Thanks in advance
Apart from what exactly your function looks like, it's not executed on hash change right now.
You use jQuery, so you can listen for hash change like this:
$(window).on('hashchange', function() {
// your locationHashChanged() function goes here
});
With this, every time the hash changes your function will be executed. The very base of your code is alright:
if (location.hash === "#player") {
// this is executed if hash changed to #player
}
if (location.hash === "#embeds") {
// this is executed if hash changed to #embeds
}
Although, inside your if blocks you declare functions (which doesn't make much sense here).
Also note that if the iframe is not from your domain, you won't be able to get any data from it. If that's the case, read more about same origin policy.

How can I combine that javascript and jQuery function to hide a button?

I downloaded the File upload script called Simple Photo Manager.
Since I'm more familiar with jQuery functions I want to use them in combination with the already existing JS code from that script.
I basically want to hide the Delete button when it's clicked.
Why is the Delete button not being hidden after I click on it?
(Note: the JS files are correctly included into the HTML file)
Also, the delLink.removeChild and delLink.appendChild are useless here because it was originally intended for a Delete/Restore switch link, but I decided to go for a button instead.
Thanks a lot if you can help me.
The html code is:
<input type='button' id='deleteit' onClick="deleteLinkOnClick
(this, 'delFlag<?=$imgid?>')">
The JS code for creating that element when an image is uploaded is:
var image_del_link = par.createElement('input');
image_del_link.type = "button";
image_del_link.value = "Delete";
imgdiv.appendChild(image_del_link);
The function for the onclick is: (I tried to write the jQuery function at the bottom)
function deleteLinkOnClick(delLink, delFlag) {
var par = window.document;
var imgDiv = delLink.parentNode;
var image_hidden = delFlag == '' ? imgDiv.childNodes[2] : par.getElementById(delFlag);
if (image_hidden.value == '1') {
image_hidden.value = '0';
delLink.removeChild(delLink.childNodes[0]);
delLink.appendChild(par.createTextNode("Restore"));
delLink.style.color = '#FF0000';
}
else {
image_hidden.value = '1';
delLink.removeChild(delLink.childNodes[0]);
delLink.appendChild(par.createTextNode("Delete"));
delLink.style.color = '#64B004';
}
$(document).ready(function(){
$(image_del_link).click(function(){
$(this).hide();
});
});
}
Here it is.
$("#deleteit").click(function(){
$(this).hide();
})
Try :
$("#deleteit").live("click", function(){
$(this).hide();
});

The onload() function refuses to run?

Hello I am sorry to bother you with such a simple question but this bit of code, I literally could not find anything wrong with it, but none of the alerts even trigger so I know that init isn't even been passed to window.onload. Here is the code:
window.onload()=init;
alert("The file has been linked to.");
function init(){
alert("Init has been loaded");
var button = document.getElementById("myButton");
button.onclick = handleButtonClick;
}
function handleButtonClick()
{
alert("button has been clicked");
var target = document.getElementById("target");
var image = document.createElement("<img />");
image.innerHTML = "<img src=../Images/banner_test.jpg alt=Banner height=42 width=42 />" ;
target.appendChild(image);
}
The JS is in a external js file I've linked to with:
<script type="text/javascript" src="../JS/Experiment.js" > </script>
Have I misspelt something or forgotten a parameter because as I've said none of the alarms will activate, no use talking about creating a new <img /> and adding it.
The HTML isn't a problem I've tried a simple alert() with inline <script> and it works but I need this to be in a external file.
window.onload is not a method, drop the parens ()
window.onload isn't a function and so the first line will prevent the rest from running:
window.onload()=init
It should be
window.onload=init;
alert("The file has been linked to.");
function init(){
alert("Init has been loaded");
var button = document.getElementById("myButton");
button.onclick = handleButtonClick;
}
function handleButtonClick()
{
alert("button has been clicked");
var target = document.getElementById("target");
var image = document.createElement("<img />");
image.innerHTML = "<img src=../Images/banner_test.jpg alt=Banner height=42 width=42 />" ;
target.appendChild(image);
}
note that also the init function is only available because JavaScript hoists non "var"ed functions to the top of the scope so watch out for this when you're pointing to functions like this.
As others have stated, the parens have to be dropped. Before your code runs fine, you have to fix more code, though.
document.createElement accepts a plain string as a parameter, which will be the tag name. Your current code will throw an error at that point.
When an image element has been created, the innerHTML property makes no sense for it. You have to explicitly attach attributes/properties to it (see below).
Fixed code:
function handleButtonClick()
{
alert("button has been clicked");
var target = document.getElementById("target");
//var image = document.createElement("<img />"); // INVALID!!
var image = new Image(); // or: document.createElement("img");
//image.innerHTML = "<img src=../Images/banner_test.jpg alt=Banner height=42 width=42 />" ;
image.src = "../Images/banner_test.jpg";
image.alt = "Banner";
image.height = 42;
image.width = 42;
target.appendChild(image);
}

External javascript File Problem

Good day!
Why is it that when I make the following javascript code external, some codes doesn't work
<form name="Keypad" action="">
</form>
var FKeyPad = document.Keypad; // DOESN'T WORK ANYMORE
var Accumulate = 0;
var FlagNewNum = false;
var PendingOp = "";
function NumPressed (Num) {
if (FlagNewNum) {
FKeyPad.ReadOut.value = Num;
FlagNewNum = false;
}
else {
if (FKeyPad.ReadOut.value == "0")
FKeyPad.ReadOut.value = Num;
else
FKeyPad.ReadOut.value += Num;
}
}
How can I make it work?
Thank you,
It has nothing to do with the code being external, it's all about when the code is executed.
You have to execute the code after the element has been created. You can put the script tag below the element in the code, or you can put the code in the handler for the window.onload event to make it run after the page has loaded:
window.onload = function() {
// your code here
};
Include your external JS file just before </body> tag and should work.
I can't find any sources which mention document.Keypad. I don't think it's supported by normal browsers.

Categories