|
Hello everyone
I’m practicing eventListener() with This dodger game
how ever when I try to move the dodger to the right side without going off the container(The dodger width is 40px) it doesn’t work here is my codepen https://codepen.io/bluesky1992-web/pen/PoeLrzJ[^]
any hint will be greatly appreciated .
|
|
|
|
|
You don't have the game object being defined. You should have a const game = document.getElementById("game"); in there. There's also a syntax error of const const causing problems. Once you define game you should see it working as expected.
Jeremy Falcon
|
|
|
|
|
Can anyone please help me. I have sidebar there are list of form fields. when I drag a field it will not fired outer drop event instead it fires the inner drop event.Inside the drop area I have added Drag and Drop Sortable List for sort the fields when the user drag the fiels.I have also added event propergation event handling but can't work. Here I attached the code
<template>
<div>
<v-card tile>
<v-row>
<v-col cols="2" class="pa-0">
<div id="component-section">
<v-expansion-panels focusable v-model="expandedPanel">
<v-expansion-panel v-for="(item, propertyName, index) in listOfFields" :key="index">
<v-expansion-panel-header style="background-color:grey;color:white">
<span> {{propertyName}} </span>
</v-expansion-panel-header>
<v-expansion-panel-content class="pa-0 drag-el" v-for="(item, Itemindex) in
listOfFields[propertyName]" :key="Itemindex">
<v-chip outlined draggable label small @dragstart="startDrag($event ,item)"
color="primary" class="ma-0 hover--class" style="border-radius:0px">
{{item.text}}
</v-chip>
</v-expansion-panel-content>
</v-expansion-panel>
</v-expansion-panels>
</div>
</v-col>
<v-col cols="10">
<div class="parent-div">
<div class="drop-zone"
<a href="https://www.codeproject.com/Members/drop">@drop</a>="onDrop($event, 1)"
@dragover.prevent @dragenter.prevent style="height:inherit;width:100%">
<v-row v-if="listOfAddedFields && listOfAddedFields.length" id='fieldDroppingArea' class="ma-2">
<template v-for="(item, index) in listOfAddedFields">
<v-col class="pa-1" :id="item.name" cols="6" :key="index">
<template v-if="item.type === 1">
<v-text-field dense outlined hide-details :label="item.name"></v-text-field>
</template>
<template v-if="item.type === 2">
<v-textarea outlined :label="item.name" dense>
</v-textarea>
</template>
</v-col>
</template>
</v-row>
</div>
</div>
</v-col>
</v-row>
</v-card>
<v-dialog v-model="dialog" fullscreen hide-overlay transition="dialog-bottom-transition">
<v-card>
<v-toolbar dense dark color="primary">
<v-btn icon fixed left="" <a href="https://www.codeproject.com/Members/cLick">@click</a>="dialog = false">
<v-icon>mdi-close</v-icon>
</v-btn>
</v-toolbar>
</v-card>
</v-dialog>
</div>
</template>
<script>
export default {
data() {
return {
dialog: false,
dragging: false,
showText: true,
dropAreaHeight: 100,
expandedPanel: 0,
isDragging: false,
listOfFields: {
standard: [{
text: 'Text field',
value: 1,
showText: true
}, {
text: 'Text area',
value: 2,
showText: true
}, {
text: 'Checkbox',
value: 3,
showText: true
}, {
text: 'Radio',
value: 4,
showText: true
}, {
text: 'Select',
value: 5,
showText: true
}, {
text: 'Date',
value: 6,
showText: true
}, {
text: 'Time',
value: 7,
showText: true
}]
},
listOfAddedFields: [{
type: 1,
name: 'text1',
},
{
type: 1,
name: 'text2',
},
{
type: 2,
name: 'texarea1',
},
{
type: 2,
name: 'texarea2',
},
{
type: 2,
name: 'texarea3',
}
],
getChildrens: []
}
},
mounted() {
this.sortingList(document.getElementById('fieldDroppingArea'))
},
methods: {
startDrag(event, item) {
this.showText = false
event.dataTransfer.dropEffect = 'move'
event.dataTransfer.effectAllowed = 'move'
event.dataTransfer.setData('itemID', item.value)
this.dragging = true
},
onDrop(event) {
console.log('mainDrop')
const itemID = event.dataTransfer.getData('itemID')
if (itemID) this.dialog = true
},
sortingList(target) {
this.getChildrens = target.children
let current = null
if (this.getChildrens.length) {
for (let i of this.getChildrens) {
i.draggable = true
i.addEventListener('dragstart', (ev) => {
console.log(i)
current = i
})
i.addEventListener('dragover', (evt) => {
evt.preventDefault()
evt.stopPropagation()
})
i.addEventListener('drop', (evt) => {
console.log('innerDrop....')
evt.preventDefault()
evt.stopPropagation()
let currentpos = 0
let droppedpos = 0
for (let it = 0; it < this.getChildrens.length; it++) {
if (current == this.getChildrens[it]) {
currentpos = it
console.log(currentpos)
}
if (i == this.getChildrens[it]) {
droppedpos = it
}
}
if (currentpos < droppedpos) {
i.parentNode.insertBefore(current, i.nextSibling);
} else {
i.parentNode.insertBefore(current, i);
}
}, true)
}
}
},
}
}
</script>
<style scoped>
.hover--class {
cursor: move;
}
.parent-div {
border:3px dashed skyblue;
margin-top:10px;
margin-right:10px;
padding:10px;
height:100%
}
</style>
modified 1-Oct-22 5:47am.
|
|
|
|
|
I'm assuming this is in Vue. You may have better luck getting an answer if you isolate the issue a bit to help us out.
Jeremy Falcon
|
|
|
|
|
First steps with creating my own JSON file...
I have this:
```
{
"videoList":[
{
"name":"Jolly Dead by Sebastion Lopez - DSB Audio Short Horror Story",
"index":0,
"thumbLink":"http://localhost/dsb/wp-content/uploads/JollyDead.webp",
"playLink": "https://youtu.be/ZUPCxQBL3Ik"
},
{
"name":"Video Two",
"index":1,
"thumbLink":"http://localhost/dsb/wp-content/uploads/Vid2.webp",
"playLink": "https://youtu.be/Vid2"
},
{
"name":"Vid Three",
"index":2,
"thumbLink":"http://localhost/dsb/wp-content/uploads/Vid3.webp",
"playLink": "https://youtu.be/Vid3"
}
]
}
I'm calling it as a script file in head section of html, in the hope of being able to parse from it in js script within body tag later on...
Seem to have fallen at the first hurdle as console says:
Uncaught SyntaxError: Unexpected token ':' (at line 2)
The JSON checks out as valid, so I'm a bit confused!
|
|
|
|
|
The JSON data will not be recognised inside the <script> tags, as the browser expects Javascript code. You should add it as a simple Javascript string, which the actual script can then parse.
|
|
|
|
|
Thanks - that makes sense. Duff info from a post i read somewhere about putting JSON in script tag.
So, I think I've converted it to js correctly:
```
const videoList = [
{
"name":"Jolly Dead by Sebastion Lopez - DSB Audio Short Horror Story",
"index":0,
"thumbLink":"http://localhost/dsb/wp-content/uploads/JollyDead.webp",
"playLink": "https://youtu.be/ZUPCxQBL3Ik"
},
{
"name":"Video Two",
"index":1,
"thumbLink":"http://localhost/dsb/wp-content/uploads/Vid2.webp",
"playLink": "https://youtu.be/Vid2"
},
{
"name":"Vid Three",
"index":2,
"thumbLink":"http://localhost/dsb/wp-content/uploads/Vid3.webp",
"playLink": "https://youtu.be/Vid3"
}
]
Throws no errors, now I'm wondering how to get the info out...
console.log(videoList[0]);
gives me all values at 0, i.e.
"name":"Jolly Dead by Sebastion Lopez - DSB Audio Short Horror Story",
"index":0,
"thumbLink":"http://localhost/dsb/wp-content/uploads/JollyDead.webp",
"playLink": "https://youtu.be/ZUPCxQBL3Ik"
was just playing around trying to get the right syntax and ended up with:
console.log(videoList,name[0])
which returns an array of all the "name" values - the comma was a mis-type!
Confused again!
|
|
|
|
|
DSB Audio (David Sweeney-Bear) wrote: Confused again! Not surprising since you are missing a lot of information. Trying to guess your way to a solution is just a waste of your time. Start with some decent tutorials and work through them until you are sure you understand what it's all about. For processing JSON in Javascript see JSON Introduction[^], on the W3Schools website, one of the best for many subjects.
|
|
|
|
|
Thanks again, having read up a bit more, I don't really need to parse from a JSON file, a simple array of objects will do the trick.
Of course that makes the title of this post non-relevant, but will post back my solution when I get it, just for completeness, in case anyone stumbles down the same blind alley I did!
|
|
|
|
|
I know you decided on a simple array. However, if you decide to try JSON in the future, I have found the
JSON.parse() function to be incredibly helpful and generally easy to use. Feel free to reach out if you try this.
|
|
|
|
|
Thanks for that, my reply is awaiting review as potential spam... probably that youtube link, I should replace it with something generic for this purpose!
|
|
|
|
|
Yes, the automatic spam catcher does not like external links in messages sometimes. And especially if you are new to the site.
|
|
|
|
|
I've now solved this little conundrum and glad to have learned a little more about arrays.
- There was no need to parse from a JSON file, really I just needed an array of objects, however, I didn't "convert" the JSON properly:
(videoList.json)
{
"videoList":[
{
"name":"Vid One",
"index":0,
"thumbLink":"assets/vid1.jpg",
"playLink": "http://some.tube/video1"
},
{
"name":"Vid Two",
"index":1,
"thumbLink":"assets/vid2.jpg",
"playLink": "https://some.tube/video2"
}
]
}
in js becomes:
(videoList.js)
var videoList = [
{
name:"Vid One",
index:0,
thumbLink:"assets/vid1.jpg",
playLink: "http://some.tube/video1"
},
{
name:"Vid Two",
index:1,
thumbLink:"assets/vid2.jpg",
playLink: "https://some.tube/video2"
}
]
(my mistake was that I failed to remove the quotations around "name")
which gives me a new array containing all the "name" values.
Moving forward, I should be able to do all sorts of useful and interesting things with my youtube videos on my site... At this moment in time, I'd rather maintain a manual list than start wrestling with the YT API!
|
|
|
|
|
JSON is pretty slick, but it took me years to get an understanding of it. I use it to store data in cookies, instead of using multiple cookies to store an array of values. And I use it to send a body payload to an API as a HTTP POST request, or to receive data from a HTTP GET request.
Anyways, you sure are doing a lot of work to create JSON. All that is really needed in Vanilla Javascript is this to create a simple JSON payload. Then you can do whatever you want with it, such as store it in a cookie, or transmit it via HTTP. As you get a feel for this, you can create more complex arrays of records.
const bodyPayload = JSON.stringify({
"cost": costValue,
"price": priceValue,
"comment": commentValue,
"operation": operation,
"from": "comments"
});
If it ain't broke don't fix it
Discover my world at jkirkerx.com
|
|
|
|
|
Hey, guys
Im new in JS, but interested in this lnguage and want to learn.
Now playing (learning) a little with charts and bumped into issue - there are two charts, but just one show the data user enter, why one? For second chart I set data from same variable, I think.
Here is the code:
<div class="chartMenu">
<p>ChartAi</p>
</div>
<div class="chartCard">
<div class="chartBox">
<div>
<canvas id="myChart"></canvas>
</div>
<div>
<canvas id="lineChart"></canvas>
</div>
<br>
<hr>
<label>Investment Sum:</label><input onchange="updateChart()" id="investmentamount" type="number" value="9000"><br>
<label>Profit sum:</label><input onchange="updateChart()" id="profitamount" type="number" value="1000"><br>
<label>Investment time:</label><input onchange="updateChart()" id="years" type="number" step="0.1" value="2.5"><br>
<br>
<hr>
<table>
<tr>
<td>Investmen Amount</td>
<td>Eur <span id="cellinvestment">9000</span></td>
</tr>
<tr>
<td>Profit Amount</td>
<td>Eur <span id="cellprofit">1000</span></td>
</tr>
<tr>
<td>Duration</td>
<td> <span id="cellyears">2.5</span></td>
</tr>
<tr>
<td>ROI in %</td>
<td> <span id="cellroi">11.11</span>%</td>
</tr>
<tr>
<td>Annualized Return:</td>
<td> <span id="cellanuallized">4.3</span>%</td>
</tr>
</table>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
const investmentamount = document.getElementById("investmentamount");
const profitamount = document.getElementById("profitamount");
const years = document.getElementById("years");
const data = {
labels: ['Investment', 'Profit'],
datasets: [{
label: 'ROI',
data: [investmentamount.value, profitamount.value],
backgroundColor: [
'rgba(255, 26, 104, 1)',
'rgba(54, 162, 235, 1)',
],
label: 'Profit',
borderColor: [
'rgba(255, 26, 104, 1)',
'rgba(54, 162, 235, 1)',
],
}]
};
const config = {
type: 'pie',
data,
options: {
}
};
const myChart = new Chart(
document.getElementById('myChart'),
config
);
const config2 = {
type: 'doughnut',
data,
options: {
}
};
const lineChart = new Chart(
document.getElementById('lineChart'),
config2
);
function updateChart() {
myChart, myChart.config.data.datasets[0].data = [investmentamount.value, profitamount.value];
myChart, myChart.update();
calculator();
};
function calculator(){
const cellinvestment = document.getElementById("cellinvestment");
cellinvestment.innerText = investmentamount.value;
const cellprofit = document.getElementById("cellprofit");
cellprofit.innerText = profitamount.value;
const cellyears = document.getElementById("cellyears");
cellyears.innerText = years.value;
const cellroi = document.getElementById("cellroi");
const roi = profitamount.value / investmentamount.value * 100;
cellroi.innerText = roi.toFixed(2);
const returnedAmount = profitamount.value + investmentamount.value;
const cellanuallized = document.getElementById("cellanuallized");
const annualizedReturn = (returnedAmount / investmentamount.value) ** (1 / parseFloat(years.value)) -1;
const annualizedPercentage = annualizedReturn * 100;
cellanuallized.innerText = annualizedPercentage.toFixed(1);
};
</script>
Help me with solvation of this issue, please!
|
|
|
|
|
Your updateChart function doesn't actually do anything with lineChart. You only update myChart inside the function, and you have no other locations that you do anything to update the chart in this code. The fix would be to do the same in updateChart, but this time with lineChart as well.
|
|
|
|
|
Thanks for answer
I was thinking about function that it does not do anything with my lineChart, thinking about how to add "lineChart " name to function, but was tired.. :#
Today after I read your reply, checked the function - it is easy to fix - I need just copy few lines of function and change the name - done it, SOLVED it!
Thank you for your reply!
P.S. thought, that maybe there are some more problems..
|
|
|
|
|
|
I'm trying to change the position of a background element on a web page in random increments each time any link on the page is clicked:
const backgroundElement = document.querySelector('.container');
const positionXY = [100, 25, 50, 75];
function randomX(positionXY) {
return positionXY[Math.floor(Math.random() * positionXY.length)]
}
function randomY(positionXY) {
return positionXY[Math.floor(Math.random() * positionXY.length)]
}
document.querySelectorAll("a").forEach(a =>
a.addEventListener("click", () => {
backgroundElement.style.cssText = `background-position: ${randomX}% ${randomY}%;`
alert("x position:" + randomX(positionXY));
alert("y position:" + randomY(positionXY));
}
)
)
the alerts show me that the values are being generated correctly, but the background position does not change on click.
Any tips? Do I need to create a toggle-state?
modified 24-Sep-22 9:45am.
|
|
|
|
|
Silly mistake really...
I needed to include the const with the function (as I did in the alerts)...
backgroundElement.style.cssText = `background-position: ${randomX(positionXY)}% ${randomY(positionXY)}%;`
This now works, but leads me on to two further questions:
1. what if the two random values are the same as the last two? the, the element would not appear to shift at all. I guess I'd need some kind of conditional setup for that
2. what if there are certain links on my page I do not want to trigger a background shift, what can I do to those links to make sure they are not included in the querySelectorAll Node List ?
|
|
|
|
|
DSB Audio (David Sweeney-Bear) wrote: 1. what if the two random values are the same as the last two? the, the element would not appear to shift at all. I guess I'd need some kind of conditional setup for that
If you want to reduce the randomness by preventing it from returning the same values twice in a row, you will indeed need to keep track of the previous values.
const backgroundElement = document.querySelector('.container');
const positionXY = [100, 25, 50, 75];
const currentPosition = { x: 0, y: 0 };
const randomPosition = (positions) => {
const result = { };
do {
result.x = positions[Math.floor(Math.random() * positions.length)];
resuly.y = positions[Math.floor(Math.random() * positions.length)];
} while (result.x === currentPosition.x && result.y === currentPosition.y);
return result;
};
const changePosition = (el, positions) => {
const newPosition = randomPosition(positions);
el.style.backgroundPosition = `${newPosition.x}% ${newPosition.y}%`;
console.debug("New position", newPosition, el);
};
document.addEventListener("click", e => {
let a = e.target;
if (a.tagName !== 'A') {
a = e.target.closest("a");
if (!a) { return; }
}
console.debug("Link clicked", a);
changePosition(backgroundElement, positionXY);
});
DSB Audio (David Sweeney-Bear) wrote: 2. what if there are certain links on my page I do not want to trigger a background shift, what can I do to those links to make sure they are not included in the querySelectorAll Node List ?
You'll need to find some way to identify those links, and exclude them from the event. For example, by using a CSS class:
document.addEventListener("click", e => {
let a = e.target;
if (a.tagName !== 'A') {
a = e.target.closest("a");
if (!a) { return; }
}
if (a.matches(".class-to-exclude")) {
return;
}
console.debug("Link clicked", a);
changePosition(backgroundElement, positionXY);
});
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Thanks, I got there in the end, although I had to modify things quite a bit to implement it in my Wordpress site:
let backgroundElement = document.querySelector('.site-container');
const positionXY = [16, 32, 48, 64, 80, 99, 66.6, 33.3, 1, 15, 30, 50, 75];
let storedXY = sessionStorage.getItem('writeXY'); let lastXY = JSON.parse(storedXY);
if (storedXY == null) {
let randomX = positionXY[Math.floor(Math.random() * positionXY.length)];
let randomY = positionXY[Math.floor(Math.random() * positionXY.length)];
document.querySelector('.site-container').style.cssText = `background-position: ${randomX}% ${randomY}%; background-size: auto;`
let randomXY = [randomX, randomY]
sessionStorage.setItem('writeXY', JSON.stringify(randomXY));
}
else if (storedXY !== null) {
let randomX = positionXY[Math.floor(Math.random() * positionXY.length)];
let randomY = positionXY[Math.floor(Math.random() * positionXY.length)];
let testX = Math.abs(randomX-lastXY[0]);
let testY = Math.abs(randomY-lastXY[1]);
let randomXY = [randomX, randomY]
sessionStorage.setItem('writeXY', JSON.stringify(randomXY));
while (testX < 16 || testY < 16) {
randomX = positionXY[Math.floor(Math.random() * positionXY.length)];
randomY = positionXY[Math.floor(Math.random() * positionXY.length)];
testX = Math.abs(randomX-lastXY[0]);
testY = Math.abs(randomY-lastXY[1]);
}
document.querySelector('.site-container').style.cssText = `background-position: ${randomX}% ${randomY}%; background-size: auto;`
randomXY = [randomX, randomY]
sessionStorage.setItem('writeXY', JSON.stringify(randomXY));
I dispensed with the onClick event in favour of pageLoad since within the WP structure, each link is a new page.
Therefore, didn't need to exclude certain anchor links, but did find that using 'a: not(".class-name")' worked to exclude links that I assigned a particular classname to.
|
|
|
|
|
correction: no pageLoad as script fires every time page loads anyway!
|
|
|
|
|
DSB Audio (David Sweeney-Bear) wrote: const positionXY = [100, 25, 50, 75];
Aside from what was already said, in the interest of readability, you'd be better off using a object (or array of objects) to act as a hash map here.
const position = { left: 100, top: 25, right: 50, bottom: 75 };
console.log(position.left);
const positions = [{ x: 100, y: 25}, { x: 50, y: 75 }];
console.log(positions[0].x);
Jeremy Falcon
modified 15-Dec-22 17:26pm.
|
|
|
|
|
I have created a web API. If someone tried to loop through thousands of requests to the server (Programmatically), would it lower the performance of the web API?
|
|
|
|
|