When to use document.Queryselector, document.getElementById
and document.getElementByClassName
Because document.getElementByID
works within the script tag of html but couldn’t work in JavaScript page. So am just confused on how to use each
Blancer.com Tutorials and projects
Freelance Projects, Design and Programming Tutorials
Category Added in a WPeMatico Campaign
When to use document.Queryselector, document.getElementById
and document.getElementByClassName
Because document.getElementByID
works within the script tag of html but couldn’t work in JavaScript page. So am just confused on how to use each
I’m running into a problem where I can’t find a solution. I have a little game plugin which is written in JavaScript. Now I would like to store the highscore in my wordpress database. Therefore I included a jQuery function in my game which is passing the score to a php file. I’m able to retrieve values from my database but weren’t able to update them. I get an 500 error in the browsers console. I first had an 404 error but I solved it with changing the url.
My javascript code:
function () {
jQuery.ajax({
url: 'wp-content/plugins/dinosaur-game/update-score.php',
type: "POST",
data: {data: this.highestScore},
});
}
My php code:
<?php
global $wpdb;
$new_score = stripslashes_deep($_POST['integerData']);
$table_name = 'wp_users';
$data = array('game_score' => $new_score);
$where = array('ID' => 5);
//$wpdb->update($table_name, $data, $where); // tried this one - 500 error
$wpdb->query("UPDATE 'wp_users' SET 'game_score' = $new_score WHERE 'ID' = 5");
?>
I used the wpdb update function and also tried to write the whole query but both produced the 500 error and the value does not update in my database. I also tried to cast the value with (int)
without success.
So I am making a tab of projects and I keep getting an error in the browser console. Although the page is rendering fine, I keep getting an error on the browser console.
Here is my Multimedia.js page
import { useEffect, useState } from "react";
import { Col, Container, Nav, Row, Tab } from "react-bootstrap";
import ProjectEmpty from "../../components/ProjectEmpty";
import ProjectCard from "../../components/ProjectCard";
export default function Multimedia() {
const [projMultimedia, setProjMultimedia] = useState();
const [projKey, setProjKey] = useState(0);
const [isMultimediaEmpty, setIsMultimediaEmpty] = useState(true);
const handleProjKeySelect = (e) => setProjKey(e);
useEffect(() => {
fetch(`${process.env.REACT_APP_API_URL}/project/all`, {
method: 'GET'
})
.then(res => res.json())
.then(data => {
setProjMultimedia(data.filter(proj => proj.category === "multimedia"));
})
}, []);
useEffect(() => {
if (typeof projMultimedia !== 'undefined' && projMultimedia.length !== 0) {
setIsMultimediaEmpty(false);
}
else {
setIsMultimediaEmpty(true);
}
}, [projMultimedia]);
return (
<Container fluid id="project-list" className="h-100">
{isMultimediaEmpty
? <ProjectEmpty />
:
<Tab.Container id="projNav" defaultActiveKey="0" activeKey={projKey} onSelect={handleProjKeySelect}>
<Row className="flex-column flex-lg-row">
<Col xs={12} lg={2} className="proj-tabs p-0 flex-shrink-1">
<Nav className="proj-nav d-lg-flex flex-lg-column">
{projMultimedia.map((project, index) => (
<Nav.Item>
<Nav.Link eventKey={index}>{project.title}</Nav.Link>
</Nav.Item>
))
}
</Nav>
</Col>
<Col xs={12} lg={10} className="proj-content px-0">
<Tab.Content className="proj-details h-100">
{projMultimedia.map((project, index) => (
<Tab.Pane eventKey={index} className="h-100"><ProjectCard key={project._id} project={project} /></Tab.Pane>
))
}
</Tab.Content>
</Col>
</Row>
</Tab.Container>
}
</Container>
);
}
Basically it fetches data from my API and then filters it based on the category. If it returns a non empty array, it should render the project card. So far it is rendering fine but this error keeps showing on my browser console.
Any idea where I’m wrong?
I just started working on a new code few days ago an I only wrote a few lines But I see this error in the console with an issue:
[I USE BRAVE BROWSER] — Screenshot –>
(https://i.stack.imgur.com/bTSwo.png)
I have no idea what the issue is and the textContent element is not even NULL.
I tried some change in code but nothing changed in the error…
I really would be appreciated if someone help me get rid of this.
I’m a beginner. I’m using a javascript to create a radar chart on my website (see the code below). And I have two separate questions, please.
What should I add to the js code to be able to change the font size/family of “VALUE1”, “VALUE2”, “VALUE3”, “VALUE4” and “VALUE5” when these values are displayed on my website ?
What should I add to the js code to be able to use custom png images in the place of the text “VALUE1”, “VALUE2”, “VALUE3”, “VALUE4” and “VALUE5” when these values are displayed on my website ?
$(function() {
var ctx = $(“#myChart”);
var data = {
labels: [“VALUE1″,”VALUE2″,”VALUE3″,”VALUE4″,”VALUE5”],
datasets: [
{
label: “DATA1”,
backgroundColor: “rgba(62,135,74,.5)”,
pointBackgroundColor: “#34b44a”,
data: [4, 4, 4, 4, 4]
}
]
};
var options = {
legend: {
display: false
},
elements: {
line: {
}
},
scale: {
angleLines: {
color: ‘#666’,
backgroundColor: ‘rgba(255,0,0,1)’,
borderColor: ‘rgba(0,255,0,1)’,
backdropColor: ‘rgba(0,255,0,1)’
},
gridLines: {
color: ‘#666’,
backgroundColor: ‘rgba(255,0,0,1)’,
borderColor: ‘rgba(0,255,0,1)’,
backdropColor: ‘rgba(0,255,0,1)’
},
pointLabels: {
fontColor: ‘#fff’
},
ticks: {
min: 0,
max: 5,
stepSize: 1,
display: false
}
},
tooltips: {
enabled: false
}
};
var myRadarChart = new Chart(ctx, {
type: ‘radar’,
data: data,
options: options
});
});
I have an RGB based darken
function that equally reduces the individual color channels by the given amount
in percentage.
/**
* Darkens the given RGB color by the specified amount.
*
* **NOTE:** The algorithm used to darken the given color is based on RGB,
* so it will not return the exact same value as the Sass `darken` function, which is based on HSL lightness.
* @param {{ r: number, g: number, b: number }} color - RGBFormat object representation of the color to darken.
* @param {number} amount - (Must be 0-100) The percentage amount to decrease equally to each of the RGB color channels.
*/
export function darken(color, amount) {
if (amount > 100) amount = 100;
else if (amount < 0) amount = 0;
const rgb = Object.assign({}, color); // copy so the object passed by reference is not mutated.
for (const [key, value] of Object.entries(rgb)) {
rgb[key] = Math.round(value * (1 - (amount / 100)));
}
return rgb;
}
For example,
If I have a color in HEX value #3498db
, Sass darken(#3498db, 10%)
wll give us #217dbb
. Which is 10% darker in HSL Lightness.
But for JS function on the other hand, darken({r: 52, g: 152, b: 219}, 10)
(This is the RGB equivalent of #3498db
) will result to {r: 47, g: 137, b: 197} which is #2f89c5
.
For now I am just using arbitrary ratio for the two darken
amount
‘s to approximate to what would seem to be the nearest result to the Sass darken
.
I have a check box field where it should be read only (checked true) after the form is saved
I tried writing a UI policy when check box is true, it is read – only.
But this is the requirement – after enabling (after saving) this option once, field has to become non editable to not disabled it in the future
I’m new to Python but I’ve been learning for several days. I have a problem and that is, after writing print(f” this letter automatically becomes italicized and it doesn’t allow me to see certain numbers in the terminal. I don’t know what to do
for j in range(3):
for k in range(2):
print(f"{j}, {k}")
Yes or yes, those quotes and the f must be in lower case, otherwise I get a syntax error.
I have registered a sync event for the service worker and defined a sync() function within the public/javascripts folder of the NodeJS application.
The function is callable from the browser’s console but service worker could not identify the function
The folder structure is as follows:
public
|- javascripts
|- ... other irrelavant js files ...
|- index.js(contains the sync() definition)
|- ... other irrelevant folders ...
|- sw.js
I have cached the files as javascripts/index.js
within the service worker.
I’m trying to call a get request using expo, but the code swears at the ssl certificate, is it possible to somehow disable the ssl certificate check, or somehow embed this certificate into the application?
A typical get request example:
const response = await fetch(`https://.....:..../......./....`, {
headers: {
Authorization: `Basic ${base64.encode(email + ':' + password)}`,
},
});
hi i am new to vue js and javascript what i am trying to is use axios onUploadProgress function in such a way that it start from 1% and goes all the way to 100 percent .
here is my code
onUploadProgress: function(progressEvent) {
let percentage=(progressEvent.loaded * 100/ (progressEvent.total + 10000000)) ;
percentage=parseInt(Math.round(percentage));
this.uploadPercentage[progress_index] = percentage;
}.bind(this)
it start from 1 % then move to 2 % and then quickly move towards 100 % what i am trying to achieve is it goes from 1 % and then to 2 % and then it moves to the 3 % and then goes on till the 100% percent i have no clue how i can acheive this if any one can help i will be thank full
I am beginning to test the components of my node.js website using chai and mocha, but when I run npm test I get this error:
‘ TypeError: request.post(…).send is not a function’
This is the code in my test.js file:
const chai = require("chai");
const expect = chai.expect;
const app = require("./app.js");
const express = require("express");
const request = express();
describe("POST /register", () => {
it("should register a new user and redirect to login page", (done) => {
const user = {
email: "[email protected]",
username: "johndoe",
password: "password",
userType: "user"
};
request.post("/register")
.send(user)
.end((err, res) => {
expect(res.status).to.equal(302);
expect(res.header.location).to.equal("/login");
done();
});
});
});
I am new to Node.js so I’m still understanding how unit tests are executed. any help would be a appreciated
I’m using vuetify + nuxt to create my web application, how could I apply an animation to a cell if its value changes?
Example:
Table example
I tried to add a ref to my table element like:
<v-data-table ref="table" :items="data" :headers="headers"/>
and then
$this.$refs.table.$el.addEventListener('change', func)
but nothing happened… anyone can give a light?
In flask app I pass my variable like that:
@app.route('/')
def index():
myvar = 1
return render_template('index.html', myvar=myvar)
In my index.html I have:
<script src='static/bundle/index.js'></script>
<script type="text/javascript">
const newvar = {{ myvar }};
console.log(myvar);
</script>
In my static/bundle/index.js it’s all the packages that are imported (if I import them directly in index.html via script tag, then it throughs an error)
My webpack.config.js:
const path = require('path');
module.exports = {
entry: {bundle: './app/static/js/app.js',
index: path.join(__dirname, './app/static/index.js'),},
resolve: {
extensions: ['.js', '.jsx']
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, './app/static/bundle/')
}
};
So when I try to access a variable in my ./app/static/index.js file with standard jinja syntax and run npm run build
:
const newvar = {{ myvar }};
console.log(myvar);
It throughs an error:
ERROR in ./app/static/index.js
Module parse failed: Unexpected token (36:20)
You may need an appropriate loader to handle this file type.
|
| const newvar = {{ myvar }};
| console.log(newvar);
|
The function below is inside another function called calculate(). The calculate function is triggered every time I press a specific button. The problem is for every time I am clicking that button the function below is generating multiple files and when I click to download, all the files generated are downloaded, which is not supposed to happen. It should only download the last generated file.
async function generateAndDownloadExcel(fillB19 = true) {
if (excelFileDownloaded) {
return;
}
// Load the template.xlsx file using fetch API
const workbook = new ExcelJS.Workbook();
const response = await fetch('ExcelTemplate.xlsx');
const arrayBuffer = await response.arrayBuffer();
// Read the Excel file from the Blob
await workbook.xlsx.load(arrayBuffer);
// Get the first sheet of the workbook
const sheet = workbook.getWorksheet(1);
// Update cell values
sheet.getCell('B6').value = pt10;
sheet.getCell('C6').value = pt11;
sheet.getCell('D6').value = pt12;
sheet.getCell('B7').value = le10;
sheet.getCell('C7').value = le11;
sheet.getCell('B8').value = fil10;
sheet.getCell('C8').value = fil11;
sheet.getCell('B9').value = trienal10;
sheet.getCell('C9').value = trienal11;
sheet.getCell('D9').value = trienal12;
sheet.getCell('B10').value = bienali10;
sheet.getCell('C10').value = bienali11;
sheet.getCell('B11').value = bienalii10;
sheet.getCell('C11').value = bienalii11;
sheet.getCell('B12').value = edf10;
sheet.getCell('C12').value = edf11;
sheet.getCell('D12').value = edf12;
sheet.getCell('D13').value = anuali;
sheet.getCell('D14').value = anualii;
sheet.getCell('E6').value = Pi1;
sheet.getCell('E7').value = Pi2;
sheet.getCell('E8').value = Pi3;
sheet.getCell('E9').value = Pi4;
sheet.getCell('E10').value = Pi5;
sheet.getCell('E11').value = Pi6;
sheet.getCell('B16').value = PPI;
sheet.getCell('B18').value = MediaFinalSecundario;
if (fillB19) {
sheet.getCell('B19').value = MediaFinalAcessoES;
}
sheet.getCell('A9').value = trienal;
sheet.getCell('A10').value = bienal_i;
sheet.getCell('A11').value = bienal_ii;
// Generate the Excel file and download it
const buffer = await workbook.xlsx.writeBuffer();
const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
let currentDate = new Date().toLocaleDateString().replaceAll('/', '-');
let fileName = `MediaCalculada[${currentDate}].xlsx`;
a.href = url;
a.download = fileName;
a.click();
setTimeout(() => URL.revokeObjectURL(url), 1000);
excelFileDownloaded = true;
}
const downloadButton = document.getElementById('downloadButton');
const downloadButtonES = document.getElementById('downloadButtonES');
downloadButton?.addEventListener('click', () => {
generateAndDownloadExcel(false);
});
downloadButtonES?.addEventListener('click', () => {
generateAndDownloadExcel();
});
}