I have a codeblock that I want to use to display projects in my portfolio that works in codepen but when I try to code it into my cargo collective site it comes back with the error that "the script is broken". The HTML and CSS are working properly only the JS is showing an error
<script>
const wheelEventName = (navigator.userAgent)
? "wheel"
: "mousewheel";
const layers = [...document.querySelectorAll(".layer")];
const tracker = document.querySelector(".track-active");
const trackerNumber = document.querySelector(".track-number");
let itemDisplayed = 0;
let animationPlaying = false;
function resetClasses() {
for (let i = 0; i < 4; i++) {
layers[0].children[i].classList.remove("item-displayed");
layers[1].children[i * 2].classList.remove("item-displayed");
}
}
document.addEventListener(wheelEventName, event => {
if (!animationPlaying) {
const nextItem = itemDisplayed + Math.sign(event.deltaY);
if (nextItem >= 0 && nextItem <= 3) {
itemDisplayed += Math.sign(event.deltaY);
layers[0].style = `transform: translateX(${-itemDisplayed * 85}vw);`;
layers[1].style = `transform: translateX(${-itemDisplayed * 85 * 2}vw);`;
layers[1].children[itemDisplayed * 2].classList.add("item-revealed");
resetClasses();
layers[0].children[itemDisplayed].classList.add("item-displayed");
layers[1].children[itemDisplayed * 2].classList.add("item-displayed");
tracker.style = `transform: translateX(${itemDisplayed * 100}%);`;
trackerNumber.innerText = `0${itemDisplayed + 1}`;
setTimeout(() => {
animationPlaying = false;
}, 2200);
animationPlaying = true;
}
}
});
</script>
Here is the codepen link that includes the HTML and CSS
https://codepen.io/pnshah115/pen/PMJBzZ
In my case I was naming a function as tryUntilDone, so I tried different changes until found the problem. There was a conflict with the name of the function. So I changed the name, and now its working:
From
function tryUntilDone () {}
to
function _tryUntilDone () {}
So the error can come from many places, but this solved my problem many times. So dont forget to try changing your variables name.
Another trick
Saving the same file more than once sometimes reports fake "script is broken" error. To avoid this error follow the steps:
Write some random code to make the script invalid. Save (it will report an error, obviously).
Reload the page
Remove the random code and save again. It will be accepted now.
Seems like executing the same script without reloading reports error and cargo thinks its an invalid script.
Related
I have a few lines of JavaScript code that pick up heading texts from separate sections and place them into their respective input fields. They are also executed on single pages using wp_enqueue_script.
It works absolutely fine when setTimeout() is used:
function passengerElevator() {
var getProductName = document.querySelectorAll('[data-id="6657316"]');
getProductName.forEach(function(item) {
var productName = item.querySelector('.lift');
var inputArea = item.querySelector('input[name=product]');
inputArea.value = productName.innerText;
});
var getProductName = document.querySelectorAll('[data-id="e9c06d5"]');
getProductName.forEach(function(item) {
var productName = item.querySelector('.lift');
var inputArea = item.querySelector('input[name=product]');
inputArea.value = productName.innerText;
});
setTimeout(function() { passengerElevator() },3000);
However, there is problem of page size (some pages have more than 10 input fields) and I don't want to set an astronomically high ms to delay the script. So I decided to fire it on DOMContentLoaded:
document.addEventListener("DOMContentLoaded", passengerElevator);
function passengerElevator() {
var getProductName = document.querySelectorAll('[data-id="6657316"]');
getProductName.forEach(function(item) {
var productName = item.querySelector('.lift'); // heading text (ex:Panoramic Lift)
var inputArea = item.querySelector('input[name=product]');
inputArea.value = productName.innerText; //ouput here
});
var getProductName = document.querySelectorAll('[data-id="e9c06d5"]');
getProductName.forEach(function(item) {
var productName = item.querySelector('.lift'); // Heading text (ex:Home Lift)
var inputArea = item.querySelector('input[name=product]');
inputArea.value = productName.innerText; // Output here
});
}
As you may have already guessed, it is not working. Is my code too messy to be executed faster or is there any other problem I am missing?
I know similar questions have been asked previously, however, no existing answer I found was able to help me.
It seems like you try to loop through elements that are still not loaded. Perhaps they are being appended to the page via Ajax, so DOMContentLoaded can't help there.
You can create your own check for those elements using setInterval, so use something like this:
let dataIdCheck = setInterval(() => {
if (document.querySelectorAll('[data-id="6657316"]').length > 0 && document.querySelectorAll('[data-id="e9c06d5"]').length > 0) {
clearInterval(dataIdCheck);
// your code here
}
}, 500);
This code will run every 500 milliseconds and check if those two elements exists, using .length. Once they do exists, we stop the interval and run the code.
I also suggest to do console.log('in') to check that our interval stop running once the elements are found.
I can't seem to get my Web Extension to block a[onclick*='ga'] as an attribute.
I've tried using
window.onload = function() {
let Removed = 0
const anchorElements = document.getElementsByTagName('A')
for (element of anchorElements) {
if (!element.getAttribute('a[onclick*='ga']')) continue
element.removeAttribute('a[onclick*='ga']')
Removed += 1
chrome.extension.sendMessage(Removed)
}
}
and
window.onload = function() {
let Removed = 0
const anchorElements = document.getElementsByTagName('A')
for (element of anchorElements) {
if (!element.getAttribute("onclick='ga'")) continue
element.removeAttribute("onclick='ga'")
Removed += 1
chrome.extension.sendMessage(Removed)
}
}
The result should be the extension removing any link with an onclick attribute of 'ga' and should then add 1 to removed which will update the extensions badge.
There are errors in your code.
Here is an example for static content. If content is generated with JavaScript, it requires additional code.
There is no need for window.onload
document.querySelectorAll('a[onclick*="ga"]').forEach(item => item.removeAttribute('onclick'));
If you want to keep a count
const a = document.querySelectorAll('a[onclick*="ga"]');
a.forEach(item => item.removeAttribute('onclick'));
chrome.runtime.sendMessage(a.length);
It is NOT a good idea to send an async message runtime.sendMessage inside the above loop.
Am using pdf-annotate.js for pdf. Its reading the content very fast but while rendering in page its very slow. How can i able to fix the problem?
My render page code:
function render()
{
PDFJS.getDocument(RENDER_OPTIONS.documentId).then(function (pdf)
{
RENDER_OPTIONS.pdfDocument = pdf;
var viewer = document.getElementById('viewer');
localStorage.getItem(RENDER_OPTIONS.documentId + '/VIEWER');
if(localStorage.getItem(RENDER_OPTIONS.documentId + '/VIEWER')){
viewer.innerHTML = localStorage.getItem(RENDER_OPTIONS.documentId + '/VIEWER');
console.log("loaded")
console.lo
}
// else {
viewer.innerHTML = '';
// }
NUM_PAGES = pdf.pdfInfo.numPages;
for (var i = 0; i < NUM_PAGES; i++)
{
console.log(i);
var page = UI.createPage(i + 1);
viewer.appendChild(page);
console.log(page)
UI.renderPage(i+1, RENDER_OPTIONS).then(function (_ref) {
console.log(_ref)
var _ref2 = _slicedToArray(_ref, 2),
pdfPage = _ref2[0],
annotations = _ref2[1];
var viewport = pdfPage.getViewport(RENDER_OPTIONS.scale, RENDER_OPTIONS.rotate);
PAGE_HEIGHT = viewport.height;
localStorage.setItem(RENDER_OPTIONS.documentId + '/HEIGHT', pdfPage.pageInfo.view[3]);
});
$("#pgloader").css("display", "none");
}
localStorage.setItem(RENDER_OPTIONS.documentId + '/VIEWER',viewer);
renderedPages.push(1);
});
}
How do i increase the rendering speed in my application. Kindly help me in this issue.
Please consider this "answer" just as an opinion piece, orientation, not a helpful answer particularly as I want to just add my 2 cents here.
We have similar problems with pdf-annotate.js, but so far this performance issue is unresolved.
What we did was, we basically split up larger/more complex PDF files page-by-page. When the user wants to see a particular page, we show a spinner as long as it's needed, processing that particular page, then when it's done, store that page in the browser's storage.
Sadly, this method doesn't fix the real problem, hence consider this as a temporary duck-tape "fix".
Please, check out this issue on GitHub regarding performance and report your case there too.
I am having an interesting issue. The general idea of what I am doing is pulling data from a Firebase database, and populating a table based on that data. Everything runs perfectly during initial population--cells and rows are populated as they should be, but the weird issue is that the scripts seem to execute again randomly. I've logged the incoming data to the console, and can see it print twice after some amount of time.
This second execution does not happen if I am to navigate between pages, or reload the page--in either of those cases everything works as it should. The problem SEEMS to happen when I log back into my computer after locking it??? Does anybody have ANY idea what could be going on here? Relevant portion of script below:
const table = document.getElementById('myTable');
firebase.auth().onAuthStateChanged(firebaseUser => {
if (firebaseUser) {
let user = firebase.auth().currentUser;
let uid = user.uid;
const dbRef = firebase.database().ref().child("data/" + uid);
dbRef.once('value', snap => {
var dataCount = snap.child("secondData").numChildren();
var datalist = snap.child("secondData").val();
var dataArray = Object.keys(datalist).map(function(k) {
return datalist[k]
});
pullAllInfo(dataCount, dataArray);
});
}
});
function pullAllInfo(count, array) {
let k = 0;
let dataArray = [];
for (i = 0; i < count; i++) {
let specificRef = firebase.database().ref().child("secondData/" + array[i]);
specificRef.once('value', snap => {
var optionsTag = array[k];
k++;
var dataId = snap.child("id").val();
var dataName = snap.child("name").val();
var dataCount = snap.child("data").numChildren();
dataArray.push(dataId, dataName, dataCount, optionsTag);
if (k == count) {
buildTable(dataArray);
console.log(dataArray);
}
});
}
}
As you can see from the code above I AM calling .once() for each reference, which would prevent data duplication from the typical .on() call. Just cant seem to figure this one out. ALSO I have an iMac, just for anyone curious about my potential computer unlock diagnosis.
Thanks all!
Most likely, the auth state is changing and setting off your function. Try throwing a log under firebase.auth().onAuthStateChanged like this:
firebase.auth().onAuthStateChanged(firebaseUser => {
console.log( 'auth state changed', firebaseUser );
if (firebaseUser) {
My guess is that you'll see that the AuthState is changing when you log out/log in from your computer.
I solved this issue by creating another global boolean called preLoaded. At the beginning, it is set to false and, once the data is loaded and passed off to build the table, it is set to true. It now looks like this:
if(k == count && preloaded == false){
preloaded = true;
console.log(dataArray);
buildTable(dataArray);
}
All set!
To give you a grasp of what I mean in my title.
Take a look at this code which is before the setInterval stopped working.
var anime = function(){
_.each(db.get('','animedb'), function(site){
var ann = function(){
^ the function is in a var
for (var epid in eps) {
epid = parseInt(epid, 10);
var eptime = (new Date(eps[epid].pubDate[0])*1000)/1000;
if(eptime > site.lastbuilddate){
counter = counter+1;
if(counter < 6){
list.push(font(colors['normal'])+eps[epid].title[0] +' - ['+ utils.secondsToString((new Date() - (eptime+site.delay))/1000, 1)+' ago.]</f>');
}
}
};
^ this is the part that breaks everything after its been edited
var run = setInterval(ann, site.interval*60000);
^ here is the setInterval its at the bottom of the each
anime();
^ here is the call for the whole function that calls the setInterval
The above code is part of an anime announcement for chat rooms owned by anime sites owners using their rss feeds.
The above code works and excuse me for saying this but at this point.
I'm going to say "I have no idea why". Because i really have no idea why setInterval picks and chooses when to work.
I talked to a friend who had more knowledge than me in javascript and time based functions and he said that there are no "conditions" required for setInterval to run.
for (var epid in eps) {
epid = parseInt(epid, 10);
var eptime = (new Date(eps[epid].pubDate[0])*1000)/1000;
if(eptime > site.lastbuilddate){
counter = counter+1;
if(counter < 6){
var url = eps[epid].link.split('//')[1];
var keyword = '';
var words = url.substr(0, url.length-1).split('/').join('-').split('-');
for (var wid in words) {
keyword += words[wid].charAt(0);
}
http.get({hostname:'dev.ilp.moe', port:80, path:'/surl/yourls-api.php?username=usernameremovedforsecurity&password=passwordremovedforsecurity&format=json&action=shorturl&url='+url+'&title='+ctitle+' - '+eps[epid].title[0]+'&keyword='+keyword}, function(r) {
if(r.statusCode === 200) { //200 is success
var b = '';
r.on('data', function(c) {
b += c;
});
r.on('end', function() {
list.push(font(colors['normal'])+eps[epid].title[0] +' - ['+ utils.secondsToString((new Date() - (eptime+site.delay))/1000, 1)+' ago.] - http://dev.ilp.moe/surl/'+keyword+'</f>');
}
}
});
}
}
};
The above code is the part for creating shorturls.
Here is the json DB that is being loaded.
{"0":{"lastbuilddate":1426441081000,"delay":0,"host":"www.animerush.tv","path":"/rss.xml","chats":["animerushtv"],"interval":15},"1":{"lastbuilddate":1424068119000,"delay":28800000,"host":"dubbedanime.tv","path":"/feed/","chats":["dubbed-anime-tv"],"interval":15},"2":{"lastbuilddate":1426415086000,"delay":32400000,"host":"bestanimes.tv","path":"/feed/","chats":["bestanimestv"],"interval":15},"3":{"lastbuilddate":1426434866000,"delay":0,"host":"www.theanime.tv","path":"/feed/","chats":["timecapsule"],"interval":15}}
The recent edit to my code was supposed to implement Shortened links for each episode released using the links provided in the rss feeds from the sites in the database.
The domain http://ilp.moe is my domain.
I have console logged everywhere and tested as much as I possibly could.
At this point I do not understand why the edit is making code that used to be executed by setInterval no longer be executed.
The reason why the code wasn't executed is because the functions were assigned to a variable so they weren't run until it got to setInterval.
When they reach setInterval the errors prevent setInterval from executing (depends on the severity of the error).
after taking the function and just running it without putting it in a var or setInterval and console logging for a bit i found the error was caused by this line
var url = eps[epid].link.split('//')[1];
in this case
eps[epid].link; // === ["http://blah.com/animelolep1"]
my problem was that the var url was trying to split on a list and not a string
here is the fix
var url = eps[epid].link[0].split('//')[1]; // grabs the first item from the list and then splits