I have a jsp file that calls a javascript function in a separate .js file. I have made an amendment to the .js function (added an alert()) and re-run the program. The alert is not called therefore the method is not called. I have renamed the method so that I get an exception but the method is successfully called. I have cleared the cache on Chrome and nothing has changed. I am using IntelliJ + embedded Tomcat.
Can anyone tell me what is going wrong?
<div id="names" style="width: 100%;"><script>myFunc();</script></div>
function myFunc(asString) {
alert("hello");
var s;
for (var i = 0; i < 10; i++) {
s += "helloAgain";
}
return s;
}
EDIT: Ok, I've found the issue. Using Firebug, I can now debug into the writePax function but... there is no alert() function. So the version I have amended is not the version being used in the app - even though the version in my exploded war has the amended version (with the alert()). Anyone know why, even after clearing my cache, all browsers are using an old .js file?
I don't know what you are trying to achieve, but this will work
<div id="names" style="width: 100%;" onClick="myFunc()">Click Me</div>
You can try it out here http://jsfiddle.net/6rQpE/
myFunc should be called as long as you put the JavaScript before the HTML.
JavaScript functions do have return values, but that's not how you insert text into the document. It has to be done entirely within JavaScript or with a framework to make it easier.
If you were using jQuery you could write something like
<script>
var myFunc = function() {
alert("Surely I was clicked");
var htmlOut = '';
for (var i = 0; i < 10; i++) { htmlOut += "hello again<br>"; }
// selects the element with "names" as the id
// and changes the html to the value of htmlOut
$("#names").html(htmlOut);
};
// this is a jquery convention, it will execute this code when the html is done loading.
$(function(){
$("button").click(myFunc);
});
</script>
Then you would put
<button>Click me</button>
somewhere in your HTML.
If you are running this as it shows in your example above I don't think you can call the function before declaring it in the file.
Example:
<div id="names" style="width: 100%;"><script>myFunc();</script></div>
function myFunc(asString) {
alert("hello");
var s;
for (var i = 0; i < 10; i++) {
s += "helloAgain";
}
return s;
}
Will not work.....
function myFunc(asString) {
alert("hello");
var s;
for (var i = 0; i < 10; i++) {
s += "helloAgain";
}
return s;
}
<div id="names" style="width: 100%;"><script>myFunc();</script></div>
Will.....
Hope that helps
My app is using a static server to serve files and it's configured to use a static version of my .js file. I've pointed my app to use local files and it is now displaying the alert().
Related
Ok so, I've got this for loop in a script tag on my EJS page. The current code looks like this:
<script async>
var removeCartItemButtons = document.getElementsByClassName('btn-danger')
console.log(removeCartItemButtons)
var i;
for (i = 0; i < removeCartItemButtons.length; i++){
console.log('elem')
var button = removeCartItemButtons[i]
button.addEventListener('click', function() {
console.log('clicked')
})
}
</script>
The console.log for the removeCartItemButtons works but the console.log('elem') doesn't run. There are no errors in my cmd nor on the developer tools. I've looked online at different forums to find people doing similar things to me and their's work fine.
I've tried multiple things, and an extra notice is that this is inside the html file and not external.
The end goal of this for loop is to loop through every element with class 'btn-danger' and log when they are clicked.
Any help would be amazing!
try running document.getElementsByClassName('btn-danger') in the console.
Additional tip: there is a for of loop in js
check this: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Statements/for...of
basically:
for(let button of removeCartItemButtons) {
button.addListener
}
I tried this code in Codepen and it worked. I rewrite your code but technically, just used a different syntax. "async" in your script tag can cause the problem, I can't be sure.
var buttons = document.querySelectorAll('.btn-danger');
[...buttons].forEach(button => {
console.log('elem')
button.addEventListener('click', function() {
console.log('clicked')
})
})
There must be an issue with your HTML code. Run the snippet below, it's working fine
var removeCartItemButtons = document.getElementsByClassName('btn-danger')
console.log(removeCartItemButtons)
var i;
for (i = 0; i < removeCartItemButtons.length; i++) {
console.log('elem')
var button = removeCartItemButtons[i]
button.addEventListener('click', function() {
console.log('clicked');
alert('clicked');
})
}
<button class='btn-danger'>Button</button>
<br/>
<button class='btn-danger'>Button</button>
<br/>
<button class='btn-danger'>Button</button>
<br/>
<button class='btn-danger'>Button</button>
removeCartItemButtons.length is 0 because when the snippet ran the DOM was not fully loaded.
Remove async and put your script at the end of your html.
Another option is to use an EventListener like onload to make sure your buttons exist before changing them.
I try to combine 2 defer functions init to 1 Java script.
I actually try now combine another one but he make conflict and the JS very heavy. this is 2 different script + 1 is not so important (but if you guys succeed help me combine all of them perfectly is be better).
This the code I try put after I edit him 2( 2 functions init ):
function init() {
var imgDefer = document.querySelectorAll('div[data-src]');
var style = "background-image: url({url})";
for (var i = 0; i < imgDefer.length; i++) {
imgDefer[i].setAttribute('style', style.replace("{url}", imgDefer[i].getAttribute('data-src')));
}
imgDefer = document.getElementsByTagName('img');
for (var i = 0; i < imgDefer.length; i++) {
if (imgDefer[i].getAttribute('data-src')) {
imgDefer[i].setAttribute('src', imgDefer[i].getAttribute('data-src'));
}
}
}
window.onload = init;
I make him a short too... he defers the images but slower the site:
function init(){for(var t=document.querySelectorAll("div[data-src]"),e=0;e<t.length;e++)t[e].setAttribute("style","background-image: url({url})".replace("{url}",t[e].getAttribute("data-src")));t=document.getElementsByTagName("img");for(e=0;e<t.length;e++)t[e].getAttribute("data-src")&&t[e].setAttribute("src",t[e].getAttribute("data-src"))}window.onload=init;
(you can look the code is deferred on the website: locksmithunit.com)
but he very slow on the page load.
and this all the original codes... these codes are for deferring images
and the last one is for "frame"
the frame not so important. and if you can give me him separately because
have pages I don't have iframe.
please help me guys, i very lost.
I most combine at least the first 2 scripts from all the 3 I send now:
<script>
function init() {
var imgDefer = document.getElementsByTagName('img');
for (var i=0; i<imgDefer.length; i++) {
if(imgDefer[i].getAttribute('data-src')) {
imgDefer[i].setAttribute('src',imgDefer[i].getAttribute('data-src'));
} } }
window.onload = init;
<script>
<script>
function init() {
var imgDefer = document.querySelectorAll('div[data-src]');
var style = "background-image: url({url})";
for (var i = 0; i < imgDefer.length; i++) {
imgDefer[i].setAttribute('style', style.replace("{url}", imgDefer[i].getAttribute('data-src')));
}
}
window.onload = init;
</script>
<script>
function init() {
var vidDefer = document.getElementsByTagName('iframe');
for (var i=0; i<vidDefer.length; i++) {
if(vidDefer[i].getAttribute('data-src')) {
vidDefer[i].setAttribute('src',vidDefer[i].getAttribute('data-src'));
} } }
window.onload = init;
</script>
ok. so I try to defer images on my website... on 120 pages...
now, when i start, i was able to defer only images.
after that, I succeed defer the background-image: url().
but it is different JS as you see on the example I post before.
I succeed combine them but still, the JS no give full power.
after that, I start to fix again pages and i notice have google maps iframe
in couple of pages. ( something like 40 pages).
and I try to defer the iframe as well but it was too much for the javascript and the website loses the page load...
the JS needs to rewriting again...
i try a couple of variations as I post before, but none of them really improve the page load.
if we sucssed fix the Javascript at least put the 2 functions inside JS, JS of the background and images you will save me because I already edit all the 120 pages and the JS work and defer, but damage the page load because the JS is not written well.
(iframe is not so important like the images and the background)
I wrote a simple javascript to change the color of an html class based on its textcontent/innerHTML. When writing the script, it works fine when I put it directly in to the developer tools console (F12) for Chrome. But when I try to call the script from a CEWP, it doesn't work. What am I missing? Here is the html I embedded in the CEWP. Long time administrator, first time diving into CSOM development. I'm sure this is something extremely simple but I am at a loss..
<script type="text/javascript">
var status_array =document.getElementsByClassName("sefl_status");
var pattern = new RegExp("Effective");
for (i=0; i < status_array.length; i++)
{
if (pattern.test(status_array[i].innerHTML)===true)
{
status_array[i].style.color="green"
}
};
</script>
I modify the code as below for your reference:
<script type="text/javascript">
window.onload=function(){
var status_array =document.getElementsByClassName("sefl_status");
var pattern = new RegExp("Effective");
for (var i=0; i < status_array.length; i++)
{
if (pattern.test(status_array[i].innerHTML)===true)
{
status_array[i].style.color="green";
}
}
}
</script>
I keep reading that it is possible to load javascript files, and then use those functions in other files. Unfortunately I can't get this to work. Here is my current path:
<script src="js/bootstrap.min.js"></script>
<script src="js/twitter_crypt.js"></script>
<script src="js/scripts.js"></script>
<script src="http://platform.twitter.com/widgets.js"></script>
<script src="js/interactive.js"></script>
I am using functions from the twitter_crypt.js file in my interactive.js file (last in path).
When I console.log(nameOfFunction) in interactive.js which is in twitter_crypt.jsit tells me that function is not defined.
I ran into this posts but I am not looking to use something like require.js .
I am just trying to call functions from the other files. I assume the must be available since I am using jquery, bootstra.min.js and other files that are being loaded.
I believe I have everything in order as well which is what this post talks about.
//Twitter_Crypt JS file:
function decoder(key, encodedMessage){
var coded = "";
var ch;
var index;
var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for(var i = 0; i < encodedMessage.length; i++){
ch = encodedMessage.charAt(i);
index = key.indexOf(ch);
if(index === -1){
coded = coded + ch;
} else {
coded = coded + alphabet.charAt(index);
}
}
return coded;
}
InteractivJS File:
$('#decodeSubmit').on("click", function(ev){
if($("#encryptText").val() === ""){
alert("Please Enter a Decrypted Tweet");
} else {
ev.preventDefault();
var decodedTweet = decoder("zipsunxmogdkfabrhcylvqewtj", $("#encryptText").val());
$("#decode_form").fadeOut("fast");
$("#decode").fadeIn("fast");
$('#decode_progress').progressbar({
display_text: 'center',
use_percentage: false,
refresh_speed: 10,
done: function($this) {
$(".modal-body").append(decodedTweet).css('color', 'black');
$("#decodeNewTweet").fadeIn("slow");
$(".modal").modal("show");
}
});
}
});
When I put the function decoder inside the interactiveJS file it works fine. When it is in the twitter_crypt.js file I keep getting a decoder is not defined.
Originally I had both scripts wrapped in a document ready, which helped but didn't solve everything. Why isn't my decoder function in global scope though? It isn't wrapped in any other functions?
Do I have to do something like window.decoder =function(){}
I'm a beginner in JS and want to know a way to simplify this code. There are 7 different divs with iframes, and also 7 different links. I have shown 1 div with iframe and 1 link. I have no idea where to start. Any help would be greatly appreciated.
NOTE: The code works to my needs, but I just need to simplify it (less js code in html, and more in js file).
JavaScript in .js file:
function show_visibility(){
for(var i = 0,e = arguments.length;i < e;i++){
var myDiv = document.getElementById(arguments[i]).style;
myDiv.display = "block";}
}
function hide_visibility(){
for(var i = 0,e = arguments.length;i < e;i++){
var myDiv = document.getElementById(arguments[i]).style;
myDiv.display = "none";}
}
function refFrame() {
for(var i = 0,e = arguments.length;i < e;i++){
document.getElementById(arguments[i]).src = document.getElementById(arguments[i]).src;
}
}
Div/iframe to be modified:
<div id="r1-box">
<iframe id="frame-box1" class="work" src="youtubelink" width="720" height="405" frameborder="0"></iframe>
</div>
Link to execute JS:
<a id="r1" href="javascript:refFrame('frame-box2','frame-box3','frame-box4','frame-box5','frame-box6','frame-box7');show_visibility('r1-box');hide_visibility('r2-box','r3-box', 'r4-box','r5-box','r6-box','r7-box');">
</a>
As a beginner you shouldn't start using jQuery until you understand Javascript more.
There are a few ways you could simplify this, the most immediate one would be to get the Javascript out of the link and into a Javascript file, or at the top of the page:
window.onload = function() {
document.getElementById('#r1').onclick = function() {
refFrame('frame-box2','frame-box3','frame-box4','frame-box5','frame-box6','frame-box7');
show_visibility('r1-box');
hide_visibility('r2-box','r3-box', 'r4-box','r5-box','r6-box','r7-box');
};
// more...
};
window.onload is an event which fires once the page has - you guessed it - finished loading. There are better ways of doing this, but this is about as basic as it gets. I'd advise you look at javascript domready?
After looking at your code a bit more, I realised all your seven links will do essentially the same thing. You can simply this by using a single function:
function refClick(id) {
var i = 7,
frames = [],
boxes = [];
while(i--) {
if(i != id) {
frames.push('frame-box' + i);
boxes.push('r' + i + '-box');
}
}
refFrame.apply(null, frames);
hide_visibility.apply(null, boxes);
show_visibility('r' + id + '-box');
}
What I'm doing here is looping through 7 times, and building an array of arguments for the refFrame and hide_visibility functions. The id variable tells the loop not to put in that id into the arrays.
Using the .apply method, I can apply an array as the arguments and call it normally.
For each of your links, you can apply the following function
document.getElementById('#r1').onclick = function() {
refClick(1);
};
document.getElementById('#r2').onclick = function() {
refClick(2);
};
//.....
You could start using jQuery.
http://jquery.com/