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>
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)
HTML:
<!DOCTYPE html>
<html>
<head>
<link rel='stylesheet' type='text/css' href='etch_a_sketch.css'/>
<script type='text/javascript' src='etch_a_sketch.js'></script>
</head>
<body>
<div class="outer">
</div>
</body>
</html>
JS:
$(document).ready(function() {
$(function() {
for(i=0; i<16; i++) {
$('<div class="inner"></div>').appendTo('.outer');
}
)};
Hello guys! I've tried looking for an answer here and elsewhere but with no luck. I'm trying to make a jquery 'for' loop that will dynamically make 16 div elements within an outer div container. The code looks sound to me but it's not working. I didn't post the CSS because it's irrelevant. Any help would be much appreciated!
First. You have syntax errors. Last line )}; should be }); .
Next. No need to create a jQuery object twice (there's a syntax too - } should be })).
This line:
$(document).ready(function() {
does the exact same thing as this line:
$(function() {
Reference
So, in summary, you should end up either with this:
$(document).ready(function() {
for(i=0; i<16; i++) {
$('<div class="inner">blah</div>').appendTo('.outer');
}
});
or this:
$(function() {
for(i=0; i<16; i++) {
$('<div class="inner">blah</div>').appendTo('.outer');
}
});
JSFiddle
Try this,
$(function() {
var innerHTML=[];
for(i=0; i<16; i++) {
innerHTML.push('<div class="inner"></div>');
}
$('.outer').html(innerHTML.join(''));
});
Please add jquery library to your page.
$(document).ready (function (){
for (var i=0; i<=16; i++){
$ ('.outer').html($('.outer').html()+"<div class='inner'></div>";
}
});
The above is seriously simple. Try that first. My theory would be that appendTo is not working because the element doesn't already exist? But it should work anyway? Also, you don't need the anonymous function within another.
You appear to be using jQuery, but haven't linked to the library. Add one of the following two lines (or download the file and link to that), depending on which version you want.
1.x snippet: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
2.x snippet: <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
Also there are some problems with brackets not being closed. The following snippet shows it working without the additional anonymous function within the ready handler.
$(document).ready(function() {
for (i = 0; i < 16; i++) {
$('<div class="inner">' + i + '</div>').appendTo('.outer');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="outer">
</div>
I want to suggest a better performance , it will speed up the process in case there is a lot of elements
$(document).ready(function() {
var innerDivs = "";
for(i=0; i<16; i++) {
innerDivs +='<div class="inner">blah</div>';
}
$('.outer').append(innerDivs);
});
This will perform better because we will not have to access the DOM tree more than one time
i'm new in firefox add-on dev
I'm triyng to run a contentscriptScript in a active tab which click on a random link into the tab, it's works
But i'm trying to repeat this operation in the new webpage in an endlessly way, like a kind of WebBot.
i dont know if i have to implement this setting in the contentScript or in the Main.js , SetInterval and SetTimeOut seems to doesnt work.
Here the ContentScript.
var webs = []; // all links
var l = document.links; //get all links
var unwebs; //new WebPage
function browse(){
// find links
for(var i=0; i<l.length; i++) {
webs.push(l[i].href);
}
//pick a random link
unwebs = webs[Math.floor(Math.random()*webs.length)];
}
function clickLink(){
//redirection
window.location.href = unwebs ;
}
$(document).ready(function(){
browse();
clickLink();
}
thank you.
See the tabs docs
main.js
var tab = require('sdk/tabs').activeTab;
tab.on('ready', function() {
//attach content script with tab.attach
});
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().