How to add dot navigation to slider - javascript

I have a working slider that I would like to add dot navigation to. However I'm not quite sure how I can pull it off. I've tried to add my own jQuery to the code, but it just breaks the slider. Does anyone have a suggestion on how to add dot navigation to the bottom of this slider?
(function () {
function init(item) {
var items = item.querySelectorAll("li"),
current = 0,
autoUpdate = true,
timeTrans = 400000000;
//create nav
var nav = document.createElement("nav");
// nav.className = "nav_arrows";
//create button prev
var prevbtn = document.createElement("button");
prevbtn.className = "fp_go_prev_slide";
prevbtn.setAttribute("aria-label", "Prev");
//create button next
var nextbtn = document.createElement("button");
nextbtn.className = "fp_go_next_slide";
nextbtn.setAttribute("aria-label", "Next");
if (items.length > 1) {
nav.appendChild(prevbtn);
nav.appendChild(nextbtn);
item.appendChild(nav);
}
items[current].className = "current_slide";
if (items.length > 1) items[items.length - 1].className = "prev_slide";
if (items.length > 1) items[current + 1].className = "next_slide";
rightClick();
var navigate = function (dir) {
items[current].className = "current_slide";
if (dir === "right") {
current = current < items.length - 1 ? current + 1 : 0;
} else if (dir === "left") {
current = current > 0 ? current - 1 : items.length - 1;
} else {
current = current > 0 ? current - 1 : items.length - 1;
}
var nextCurrent = current < items.length - 1 ? current + 1 : 0,
prevCurrent = current > 0 ? current - 1 : items.length - 1;
items[current].className = "current_slide";
items[prevCurrent].className = "prev_slide";
items[nextCurrent].className = "next_slide";
if (dir === "right") {
rightClick();
}
if (dir === "left") {
leftClick();
}
};
item.addEventListener("mouseenter", function () {
autoUpdate = false;
});
item.addEventListener("mouseleave", function () {
rightClick();
autoUpdate = true;
});
setInterval(function () {
if (autoUpdate) navigate("right");
}, timeTrans);
prevbtn.addEventListener("click", function () {
navigate("left");
});
nextbtn.addEventListener("click", function () {
navigate("right");
});
function rightClick() {
var n = document.getElementsByClassName("next_slide");
var c = document.getElementsByClassName("current_slide");
var p = document.getElementsByClassName("prev_slide");
}
function leftClick() {
var n = document.getElementsByClassName("next_slide");
var c = document.getElementsByClassName("current_slide");
var p = document.getElementsByClassName("prev_slide");
}
}
[].slice
.call(document.querySelectorAll(".fp_slider_container_top_main"))
.forEach(function (item) {
init(item);
});
})();
And here's the html
<section class="featured-project-slider">
<div class="row fp-top-slider">
<div class="col-lg-8 fp-front-left">
<h1 class="fp-header extended-black-l">Featured Projects</h1>
</div>
<div class="col-lg-4 fp-front-right">
<button class="top-right-button extended-black-s">See all projects ></button>
</div>
<div class="col-lg-10 offset-lg-1 col-12 fp-center">
<!-- // * Slider starts -->
<section class="fp_slider_container_top_main">
<!-- all slides container starts -->
<ul class="fp_slider_container_top">
<?php $loop = new WP_Query(array('post_type' => 'project', 'cat' => '4', 'orderby' => 'ID', 'order' => 'ASC' )); ?>
<?php while ($loop->have_posts()): $loop->the_post(); ?>
<!-- slide starts -->
<li>
<div class="fp_slider_container_top_img_container">
<img src="<?php the_field('top_image'); ?>" alt="slider image" class="fp_slider_container_top_img"
loading="lazy">
<div class="fp-project-box">
<p class="fp-small extended-black-s">Our History</p>
<h1 class="condensed-semibold-l"><?php echo the_title(); ?></h1>
<p class="regular-m"><?php the_field('short_description'); ?></p>
<button class="extended-black-s">Learn More ></button>
</div>
</div>
</li>
<!-- slide ends -->
<?php endwhile;
wp_reset_query(); ?>
<?php
?>
</ul>
<!-- all slides container ends -->
</section>
<!-- // * Slider ends -->
</div>
<div class="col-lg-6 offset-lg-6 col-12 fp-front-right-red">
<div>
</div>
</section>

Related

Trigger function to roll a dice

I have a function to get a random value (1->6) to roll a dice:
const rollDice = () => {
document.dispatchEvent(
new CustomEvent('rollDice', {
detail: { value: Math.floor(Math.random() * 6) + 1 },
bubbles: true,
cancelable: false
})
);
};
Get the value from rollDice() and put in the correct positions, but I don't know why it work incorrectly. The result need show as the picture:
Result
I am newbie here, Can anyone help point out where I'm going wrong?
const rollDice = () => {
document.dispatchEvent(
new CustomEvent('rollDice', {
detail: {
value: Math.floor(Math.random() * 6) + 1
},
bubbles: true,
cancelable: false
})
);
};
let btn = document.querySelector("#roll-button");
btn.addEventListener('click', function() {
var varones = toNumber(parseInt(document.querySelector("#ones p").textContent));
var vartwos = toNumber(parseInt(document.querySelector("#twos p").textContent));
var varthrees = toNumber(parseInt(document.querySelector("#threes p").textContent));
var varfours = toNumber(parseInt(document.querySelector("#fours p").textContent));
var varfives = toNumber(parseInt(document.querySelector("#fives p").textContent));
var varsixes = toNumber(parseInt(document.querySelector("#sixes p").textContent));
rollDice();
document.addEventListener('rollDice', (e) => {
alert(e.detail.value);
if (e.detail.value == 1) {
varones = varones + 1;
}
if (e.detail.value == 2) {
vartwos = vartwos + 1;
}
if (e.detail.value == 3) {
varthrees = varthrees + 1;
}
if (e.detail.value == 4) {
varfours = varfours + 1;
}
if (e.detail.value == 5) {
varfives = varfives + 1;
}
if (e.detail.value == 6) {
varsixes = varsixes + 1;
}
total = varones + vartwos + varthrees + varfours + varfives + varsixes;
document.querySelector("#ones p").textContent = varones;
document.querySelector("#twos p").textContent = vartwos;
document.querySelector("#threes p").textContent = varthrees;
document.querySelector("#fours p").textContent = varfours;
document.querySelector("#fives p").textContent = varfives;
document.querySelector("#sixes p").textContent = varsixes;
document.querySelector("#totals p span").textContent = total;
});
});
function toNumber(a) {
if (isNaN(a)) {
a = 0;
}
return a;
}
<h1>Events Triggered and Emitted</h1>
<h2>Dice Rolls</h2>
<div id="rolls">
<div id="ones">
<span class="dice">⚀</span>
<p>-</p>
</div>
<div id="twos">
<span class="dice">⚁</span>
<p>-</p>
</div>
<div id="threes">
<span class="dice">⚂</span>
<p>-</p>
</div>
<div id="fours">
<span class="dice">⚃</span>
<p>-</p>
</div>
<div id="fives">
<span class="dice">⚄</span>
<p>-</p>
</div>
<div id="sixes">
<span class="dice">⚅</span>
<p>-</p>
</div>
<div id="dice">
<button id="roll-button"><span class="dice">⚂</span></button>
</div>
<div id="totals">
<p>Total rolls: <span>0</span></p>
</div>
</div>
<!-- Template for dice roll 1 -->
<template id="template1"><span class="dice">⚀</span></template>
<!-- Template for dice roll 2 -->
<template id="template2"><span class="dice">⚁</span></template>
<!-- Template for dice roll 3 -->
<template id="template3"><span class="dice">⚂</span></template>
<!-- Template for dice roll 4 -->
<template id="template4"><span class="dice">⚃</span></template>
<!-- Template for dice roll 5 -->
<template id="template5"><span class="dice">⚄</span></template>
<!-- Template for dice roll 6 -->
<template id="template6"><span class="dice">⚅</span></template>
I don't understand all your code, but I think you should write your rollDice event listener out of you click button event listener, because in your example, the event is triggered before the document is listening to this event.
btn.addEventListener('click', () => {
// do something
rollDice()
})
document.addEventListener('rollDice', () => {
// do something
})
First of all, don't type more code than necessary inside an eventListener. If you had refactored your code into a method, you would see that you tried to create an event listener inside an event listener. Here is how an eventListener should be set up:
btn.addEventListener('click', rollDice);
I don't understand why you created an event listener inside rollDice(). Was that part of an assignment? I just called the correct method straight away.
The second part I did was to try to reduce code by looking at similarities in the code. I can use the :nth-child selector to get the proper dice container by using the randomized roll.
rollsDiv.querySelector(`div:nth-child(${roll}) > p`)
The third thing to remember, is to write as short methods as possible, by having them do at most one thing. If you can't do that, try to write methods as a table of content. A person should be able to read the code and understand what's happening just by how it's written. That means refactor complex code, like getCorrectDiceElement(), or using variables and naming them to make each row comprehensible.
These are more tips for intermediate coding, but it could be nice to know this on beforehand. Otherwise, you won't understand your own code when looking at it after a half year. :)
As a present, I added a four more lines (a, b) for functionality that I guess you would like to implement in the future. Good luck!
const rollsDiv = document.getElementById("rolls");
// const totalsDiv = document.getElementById("totals"); // a
const btn = document.getElementById("roll-button");
// var numberOfRolls = 0; // a
const randomize = (max = 6, min = 1) => {
return Math.floor(Math.random() * max) + min;
};
const rollDice = () => {
var roll = randomize();
let diceElement = getCorrectDiceElement(roll);
let previousNumber = toNumber(diceElement.textContent);
// let diceSymbol = document.getElementById("template" + roll).textContent; // b
// console.log(roll, diceElement.parentNode.id)
previousNumber++;
// numberOfRolls++; // a
diceElement.textContent = previousNumber;
}
const getCorrectDiceElement= (roll) => {
return rollsDiv.querySelector(`div:nth-child(${roll}) > p`)
}
function toNumber(a) {
return isNaN(a) ? 0 : a;
}
btn.addEventListener('click', rollDice);
#rolls {
display: flex;
margin-bottom: 1rem;
}
#rolls > div,
#roll-button
{
text-align: center;
font-size: 2rem;
padding: 0rem 1rem;
}
#rolls p {
margin: 0;
}
<h2>Dice Rolls</h2>
<div id="rolls">
<div id="ones">
<span class="dice">⚀</span>
<p>-</p>
</div>
<div id="twos">
<span class="dice">⚁</span>
<p>-</p>
</div>
<div id="threes">
<span class="dice">⚂</span>
<p>-</p>
</div>
<div id="fours">
<span class="dice">⚃</span>
<p>-</p>
</div>
<div id="fives">
<span class="dice">⚄</span>
<p>-</p>
</div>
<div id="sixes">
<span class="dice">⚅</span>
<p>-</p>
</div>
</div>
<div>
<div id="dice">
<button id="roll-button">Roll</button>
</div>
<div id="totals">
<p>Total rolls: <span>0</span></p>
</div>
</div>
<!-- Template for dice roll 1 -->
<template id="template1"><span class="dice">⚀</span></template>
<!-- Template for dice roll 2 -->
<template id="template2"><span class="dice">⚁</span></template>
<!-- Template for dice roll 3 -->
<template id="template3"><span class="dice">⚂</span></template>
<!-- Template for dice roll 4 -->
<template id="template4"><span class="dice">⚃</span></template>
<!-- Template for dice roll 5 -->
<template id="template5"><span class="dice">⚄</span></template>
<!-- Template for dice roll 6 -->
<template id="template6"><span class="dice">⚅</span></template>
[EDIT] Added back the original rollDice() method.
const rollsDiv = document.getElementById("rolls");
// const totalsDiv = document.getElementById("totals"); // a
const btn = document.getElementById("roll-button");
// var numberOfRolls = 0; // a
const randomize = (max = 6, min = 1) => {
return Math.floor(Math.random() * max) + min;
};
const rollDice = () => { // NEW
let eventName = "rollDice";
let eventDetail = {'value': randomize()};
let eventProperties = {detail: eventDetail, 'bubbles': true, 'cancelable': false};
let customEvent = new CustomEvent(eventName, eventProperties);
document.dispatchEvent(customEvent);
};
const handleDiceResult = (event) => {
var eventDetail = event.detail; // NEW
var roll = eventDetail.value;
let diceElement = getCorrectDiceElement(roll);
let previousNumber = toNumber(diceElement.textContent);
// let diceSymbol = document.getElementById("template" + roll).textContent; // b
// console.log(roll, diceElement.parentNode.id)
previousNumber++;
// numberOfRolls++; // a
diceElement.textContent = previousNumber;
}
const getCorrectDiceElement= (roll) => {
return rollsDiv.querySelector(`div:nth-child(${roll}) > p`);
}
function toNumber(a) {
return isNaN(a) ? 0 : a;
}
btn.addEventListener('click', rollDice);
document.addEventListener('rollDice', handleDiceResult); // NEW
#rolls {
display: flex;
margin-bottom: 1rem;
}
#rolls > div,
#roll-button
{
text-align: center;
font-size: 2rem;
padding: 0rem 1rem;
}
#rolls p {
margin: 0;
}
<h2>Dice Rolls</h2>
<div id="rolls">
<div id="ones">
<span class="dice">⚀</span>
<p>-</p>
</div>
<div id="twos">
<span class="dice">⚁</span>
<p>-</p>
</div>
<div id="threes">
<span class="dice">⚂</span>
<p>-</p>
</div>
<div id="fours">
<span class="dice">⚃</span>
<p>-</p>
</div>
<div id="fives">
<span class="dice">⚄</span>
<p>-</p>
</div>
<div id="sixes">
<span class="dice">⚅</span>
<p>-</p>
</div>
</div>
<div>
<div id="dice">
<button id="roll-button">Roll</button>
</div>
<div id="totals">
<p>Total rolls: <span>0</span></p>
</div>
</div>
<!-- Template for dice roll 1 -->
<template id="template1"><span class="dice">⚀</span></template>
<!-- Template for dice roll 2 -->
<template id="template2"><span class="dice">⚁</span></template>
<!-- Template for dice roll 3 -->
<template id="template3"><span class="dice">⚂</span></template>
<!-- Template for dice roll 4 -->
<template id="template4"><span class="dice">⚃</span></template>
<!-- Template for dice roll 5 -->
<template id="template5"><span class="dice">⚄</span></template>
<!-- Template for dice roll 6 -->
<template id="template6"><span class="dice">⚅</span></template>

Check if true or false on json parse into html

Currently have all data displaying perfectly except the boolean ones.
I have some data that if true or false they should display different html/css
So, how can I have a class or html that shows the data if returns true?
I'm a bit stuck on parsing this data on this code. As I was on the right direction until this new request.
The Json loooks like this:
{
"name": "Serena Gosling",
"supporterNumber": "0123456789",
"isStrongRelationship": true,
"ticketingPoints" :"2,500 Ticket Points",
"thumbnailUrl": "https://i.pravatar.cc/100"
},
fetch("supporters.json")
.then(response => response.json())
.then(supporters => {
localStorage.setItem("supporters", JSON.stringify(supporters));
});
let container = document.querySelector(".content");
let loadMoreButton = document.querySelector(".content button");
let initialItems = 4;
let loadItems = 2;
function loadInitialItems() {
let supporters = JSON.parse(localStorage.getItem("supporters"));
let out = "";
let counter = 0;
for (let supporter of supporters) {
if (counter < initialItems) {
out += `
<div class="supporter">
<h4 class="supporter__name">
<span class="supporter__thumbnail"></span>
${supporter.name}
${supporter.relationship}
<span class="supporter__number">(${supporter.supporterNumber})</span>
</h4>
<span class="supporter__points">${supporter.ticketingPoints}</span>
</div>
`;
}
counter++;
}
let div = document.createElement("div");
container.insertBefore(div, loadMoreButton);
div.innerHTML = out;
}
function loadData() {
let supporters = JSON.parse(localStorage.getItem("supporters"));
let currentDisplayedItems = document.querySelectorAll(".supporter").length;
let out = "";
let counter = 0;
for (let supporter of supporters) {
if (counter >= currentDisplayedItems && counter < loadItems + currentDisplayedItems) {
out += `
<div class="supporter">
<h4 class="supporter__name">
<span class="supporter__thumbnail"></span>
${supporter.name}
${supporter.relationship}
<span class="supporter__number">(${supporter.supporterNumber})</span>
</h4>
<span class="supporter__points">${supporter.ticketingPoints}</span>
</div>
`;
}
counter++;
}
let div = document.createElement("div");
container.insertBefore(div, loadMoreButton);
div.innerHTML = out;
div.style.opacity = 0;
if (document.querySelectorAll(".supporter").length == supporters.length) {
loadMoreButton.style.display = "none";
}
fadeIn(div);
}
function fadeIn(div) {
let opacity = 0;
let interval = setInterval(function() {
if (opacity <= 1) {
opacity = opacity + 0.1;
div.style.opacity = opacity;
} else {
clearInterval(interval);
}
}, 30);
}
loadInitialItems()
<div class="content">
<!-- content displaye from the javascript file -->
<button onclick="loadData()" class="load-more-button"><span>❭</span> </button>
</div>
You can use a ternary expression in the template literal.
out += `
<div class="supporter">
<h4 class="supporter__name">
<span class="supporter__thumbnail"></span>
${supporter.name}
${supporter.relationship}
<span class="supporter__number">(${supporter.supporterNumber})</span>
</h4>
<span class="supporter__points">${supporter.ticketingPoints}</span>
<span class="supporter__relationship">${supporter.isStrongRelationship ? "Strong" : "Weak"} relationship</span>
</div>
`;

Play audio file based on id from mysql database

I have this audio player script that plays audio files, but i don't know how to play the files individually based on id from mysql database. I have a datatable and all the files listed there with a play button to make an idea. Thanks
Codepen audio player script:
https://codepen.io/abxlfazl/pen/YzGEVRP
Here is the audio script:
PHP:
<?php
$qnm = $db->query("SELECT * FROM `".RDCP_PREFIX."muzica` WHERE uid = ".$uid." ");
while ($row = $db->fetch($qnm)) {
$id = $row['mid']; // music id
$locatiem = $row['locatie'];
$numeclubs = $row['numeclub'];
$numecoregrafiem = $row['numecoregrafie'];
$piesa = str_replace("muzica/", "", $locatiem); // music file track
?>
HTML:
<div class="modal plyer fade delmusic<?php echo $id;?>" tabindex="-1" id="delmusic<?php echo $id; ?>"
track="<?php echo $id;?>" aria-labelledby="myDefaultModalLabel">
<div class="container" style="margin-top: 332px;display: flex;">
<div class="player">
<div class="player__header">
<div class="player__img player__img--absolute slider">
<button class="player__button player__button--absolute--nw playlist">
<img src="../../../dt/app-assets/images/elements/musicplayer/playlist.svg" alt="playlist-icon">
</button>
<button class="player__button player__button--absolute--center play">
<img src="../../../dt/app-assets/images/elements/musicplayer/play.svg" alt="play-icon">
<img src="../../../dt/app-assets/images/elements/musicplayer/pause.svg" alt="pause-icon">
</button>
<div class="slider__content">
<img class="img slider__img" src="http://physical-authority.surge.sh/imgs/1.jpg" alt="cover">
</div>
</div>
<div class="player__controls">
<button class="player__button back">
<img class="img" src="../../../dt/app-assets/images/elements/musicplayer/back.svg" alt="back-icon">
</button>
<p class="player__context slider__context">
<strong class="slider__name"></strong>
<span class="player__title slider__title"></span>
</p>
<button class="player__button next">
<img class="img" src="../../../dt/app-assets/images/elements/musicplayer/next.svg" alt="next-icon">
</button>
<div class="progres">
<div class="progres__filled"></div>
</div>
</div>
</div>
<ul class="player__playlist list">
<li class="player__song s<?php echo $id;?>">
<img class="player__img img" src="http://physical-authority.surge.sh/imgs/1.jpg" alt="cover">
<p class="player__context">
<b class="player__song-name"><?php echo $numecoregrafiem; ?></b>
<span class="flex">
<span class="player__title"><?php echo $numeclubs; ?></span>
</span>
</p>
<audio class="audio" src="<?php echo "dt/pagini/momente/momente/".$locatiem; ?>"></audio>
</li>
</ul>
</div>
</div>
</div>
Javascript:
const bgBody = ["#e5e7e9", "#ff4545", "#f8ded3", "#ffc382", "#f5eda6", "#ffcbdc", "#dcf3f3"];
const body = document.body;
const player = document.querySelector(".player");
const playerHeader = player.querySelector(".player__header");
const playerControls = player.querySelector(".player__controls");
const playerPlayList = player.querySelectorAll(".player__song");
const playerSongs = player.querySelectorAll(".audio");
const playButton = player.querySelector(".play");
const nextButton = player.querySelector(".next");
const backButton = player.querySelector(".back");
const playlistButton = player.querySelector(".playlist");
const slider = player.querySelector(".slider");
const sliderContext = player.querySelector(".slider__context");
const sliderName = sliderContext.querySelector(".slider__name");
const sliderTitle = sliderContext.querySelector(".slider__title");
const sliderContent = slider.querySelector(".slider__content");
const sliderContentLength = playerPlayList.length - 1;
const sliderWidth = 100;
let left = 0;
let count = 0;
let song = playerSongs[count];
let isPlay = false;
const pauseIcon = playButton.querySelector("img[alt = 'pause-icon']");
const playIcon = playButton.querySelector("img[alt = 'play-icon']");
const progres = player.querySelector(".progres");
const progresFilled = progres.querySelector(".progres__filled");
let isMove = false;
function closePlayer() {
playerHeader.classList.remove("open-header");
playerControls.classList.remove("move");
slider.classList.remove("open-slider");
}
function next(index) {
count = index || count;
if (count == sliderContentLength) {
count = count;
return;
}
left = (count + 1) * sliderWidth;
left = Math.min(left, (sliderContentLength) * sliderWidth);
sliderContent.style.transform = `translate3d(-${left}%, 0, 0)`;
count++;
run();
}
function back(index) {
count = index || count;
if (count == 0) {
count = count;
return;
}
left = (count - 1) * sliderWidth;
left = Math.max(0, left);
sliderContent.style.transform = `translate3d(-${left}%, 0, 0)`;
count--;
run();
}
function changeSliderContext() {
sliderContext.style.animationName = "opacity";
sliderName.textContent = playerPlayList[count].querySelector(".player__title").textContent;
sliderTitle.textContent = playerPlayList[count].querySelector(".player__song-name").textContent;
if (sliderName.textContent.length > 16) {
const textWrap = document.createElement("span");
textWrap.className = "text-wrap";
textWrap.innerHTML = sliderName.textContent + " " + sliderName.textContent;
sliderName.innerHTML = "";
sliderName.append(textWrap);
}
if (sliderTitle.textContent.length >= 18) {
const textWrap = document.createElement("span");
textWrap.className = "text-wrap";
textWrap.innerHTML = sliderTitle.textContent + " " + sliderTitle.textContent;
sliderTitle.innerHTML = "";
sliderTitle.append(textWrap);
}
}
function selectSong() {
song = playerSongs[count];
for (const item of playerSongs) {
if (item != song) {
item.pause();
item.currentTime = 0;
}
}
if (isPlay) song.play();
}
function run() {
changeSliderContext();
selectSong();
}
function playSong() {
if (song.paused) {
song.play();
playIcon.style.display = "none";
pauseIcon.style.display = "block";
}else{
song.pause();
isPlay = false;
playIcon.style.display = "";
pauseIcon.style.display = "";
}
}
function progresUpdate() {
const progresFilledWidth = (this.currentTime / this.duration) * 100 + "%";
progresFilled.style.width = progresFilledWidth;
if (isPlay && this.duration == this.currentTime) {
next();
}
if (count == sliderContentLength && song.currentTime == song.duration) {
playIcon.style.display = "block";
pauseIcon.style.display = "";
isPlay = false;
}
}
function scurb(e) {
// If we use e.offsetX, we have trouble setting the song time, when the mousemove is running
const currentTime = ( (e.clientX - progres.getBoundingClientRect().left) / progres.offsetWidth ) * song.duration;
song.currentTime = currentTime;
}
function durationSongs() {
let min = parseInt(this.duration / 60);
if (min < 10) min = "0" + min;
let sec = parseInt(this.duration % 60);
if (sec < 10) sec = "0" + sec;
const playerSongTime = `${min}:${sec}`;
}
changeSliderContext();
// add events
sliderContext.addEventListener("animationend", () => sliderContext.style.animationName ='');
playlistButton.addEventListener("click", closePlayer);
nextButton.addEventListener("click", () => {
next(0)
});
backButton.addEventListener("click", () => {
back(0)
});
playButton.addEventListener("click", () => {
isPlay = true;
playSong();
});
playerSongs.forEach(song => {
song.addEventListener("loadeddata" , durationSongs);
song.addEventListener("timeupdate" , progresUpdate);
});
progres.addEventListener("pointerdown", (e) => {
scurb(e);
isMove = true;
});
document.addEventListener("pointermove", (e) => {
if (isMove) {
scurb(e);
song.muted = true;
}
});
document.addEventListener("pointerup", () => {
isMove = false;
song.muted = false;
});
playerPlayList.forEach((item, index) => {
item.addEventListener("click", function() {
if (index > count) {
next(index - 1);
return;
}
if (index < count) {
back(index + 1);
return;
}
});
});
You could put the track ID into an attribute like "data-track" then retrieve it and send out an ajax request to a php page which will do your DB query and return the info you want.
// User selects track to play
$(".track").on('click', function(e){
track = $(this).data("track");
var data = {
trackId: track
};
$.ajax({
url: 'getTrack.php',
type: 'post',
data: data,
}).done(function(result){
// parse data from response and load your player's modal
}).fail(function(data){
// Uh-oh!
}).always(function(){
// Do something
});
});

how does forEach works in this case?

I have 2 buttons which they activate/deactivate divs, button next activate next div and button prev deactivate current div.
function update gets called in each click, im trying to understand how comparing the index of the array and currentActive is helping us in this case.
I comment out the rest of the code to follow the value of idx but I get confused with the output....................
const progress = document.getElementById('progress');
const prev = document.getElementById('prev');
const next = document.getElementById('next');
const circles = document.querySelectorAll('.circle');
let currentActive = 1;
next.addEventListener('click', () => {
currentActive++;
if (currentActive > circles.length) {
currentActive = circles.length;
}
update();
});
prev.addEventListener('click', () => {
currentActive--;
if (currentActive < 1) {
currentActive = 1;
}
update();
});
function update() {
console.log(' - - - - - - - - ')
console.log('update function, currentActive = '+ currentActive )
circles.forEach((circle, idx) => {
console.log('idx->'+ idx + ', ==Active?->' + (idx===currentActive) + ', div->' + circle.textContent )
// if (idx < currentActive) {
// console.log('index is:' + idx, 'current is :' + currentActive);
// circle.classList.add('active');
// }
/* else {
circle.classList.remove('active');
}
});
if (currentActive === 1) {
prev.disabled = false;
} else if (currentActive === circles.length) {
next.disabled = true;
prev.disabled = false;
} else {
prev.disabled = false;
next.disabled = false;
} */
});
}
.as-console-wrapper {
top : 0;
left : 30% !important;
max-height : 100% !important;
width : 70%;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css" integrity="sha512-+4zCK9k+qNFUR5X+cKL9EIR+ZOhtIloNl9GIKS57V1MyNsYpYcUrUeQc9vNfzsWfV28IaLL3i96P9sdNyeRssA==" crossorigin="anonymous" />
<link rel="stylesheet" href="style.css" />
<title>Progress Steps</title>
<div class="container">
<div class="progress-container">
<div class="progress" id="progress"></div>
<div class="circle active">1</div>
<div class="circle">2</div>
<div class="circle">3</div>
<div class="circle">4</div>
</div>
<button class="btn" id="prev" disabled>Prev</button>
<button class="btn" id="next">Next</button>
</div>
</head>
<body>
<script src="script.js"></script>
</body>
</html>
I think what bothers you is that in computing, the first index of a list is zero.
here is your code (revisited)
const progress = document.getElementById('progress')
, bt_prev = document.getElementById('prev')
, bt_next = document.getElementById('next')
, divs_circle = document.querySelectorAll('.circle')
, Last_circle = divs_circle.length -1
, progressText =
[ 'payment first step'
, 'payment second step'
, 'payment third step'
, 'payment last step'
, 'payment done !'
]
;
var currentActive = 0 // the first index is zero
;
function setActivCircle()
{
divs_circle.forEach((circle, idx )=>
{
if ( idx === currentActive ) circle.classList.add('active')
else circle.classList.remove('active')
if( idx < currentActive ) circle.classList.add('done')
else circle.classList.remove('done')
})
progress.textContent = progressText[currentActive]
bt_prev.disabled = (currentActive === 0) || (currentActive > Last_circle)
bt_next.disabled = (currentActive > Last_circle)
bt_next.textContent = (currentActive === Last_circle) ? 'Terminate' : 'Next'
console.clear()
console.log(`currentActive value is ${currentActive}, last Idx value is ${Last_circle}`)
}
setActivCircle() // first attempt
bt_next.onclick = () =>
{
++currentActive
setActivCircle()
}
bt_prev.onclick = () =>
{
--currentActive
setActivCircle()
}
div.circle {
padding : .2em;
width : 5em;
border : 1px solid grey;
margin : .2em;
}
div.active {
background-color : lightblue;
}
div.done {
background-color : lightgreen;
}
<div class="container">
<div class="progress-container">
<div class="progress" id="progress"></div>
<div class="circle" >1</div>
<div class="circle" >2</div>
<div class="circle" >3</div>
<div class="circle" >4</div>
</div>
<button class="btn" id="prev" > Prev</button>
<button class="btn" id="next" > Next</button>
</div>
“….im trying to understand how comparing the index of the array and currentActive is helping us in this case.”
Think your first idx is 0, and onload your currentActive=1 then your condition is saying if idx<currentActive , it will receive a class active.
Now see what happens when you click the next,
As your currentActive is 1 onload, when you click next then happens currentActive++ that makes 2, now see your condition, if idx<currentActive (this time idx is 1) and the condition is true, so it will receive a class active, but the prev will remove the class active (and on each click it resets the values as per your condition) …. Now see your other codes and try to understand also the prev click and other codes.

opencart 1.5.6.4 disable page cache for module

How to disable the Cache for part of page? There is a block that is updated dynamically, but I can't seem to disable its caching... module with feedbacks and when ceche is enable feedbacks stop showing on random ...
Perhaps I'm missing something in full page caching mechanics?
Please help.
controller :
$this->load->model('catalog/review');
$current_store = $this->config->get('config_store_id');
$feedbacks = $this->model_catalog_review->getFeedbacksByStore($current_store);
$this->data['feedbackscrazys'][] = array(
'feedback_name' => $feedbacks['form_name'],
'feedback_text' => $feedbacks['feedback']
);
$this->response->setOutput($this->render());
model:
public function getFeedbacksByStore($id) {
$sql = "SELECT * FROM " . DB_PREFIX . "feedbackcrazy";
$sql .= " WHERE shop_id = ".$id." AND show_index=1";
$sql .= " ORDER BY shop_id asc";
$query = $this->db->query($sql);
return $query->row;
}
and the index.php
<div class="col-md-53 col-sm-55 col-xs-55 all-paddtop18">
<div class="contentItem">
<div id="footerfeedback" class="group">
<div id="footerfeedbackContentBox">
<div id="footerfeedbackTitle">
<span id="footerfeedbackYourWord">YOUR</span>
<span id="footerfeedbackOpinionsWord">FEEDBACK</span>
</div>
<div id="footerfeedbackContent" class="group">
<div id="footerfeedbackItem">
<div id="footerfeedbackItemContent">
...
</div>
<div id="footerfeedbackItemDivider">-</div>
<div id="footerfeedbackItemCustomer">...</div>
</div>
</div>
</div>
<div id="footerfeedbackShareButton">
Share your opinion
</div>
</div>
</div>
</div>
javascript:
$(document).ready(function() {
var feedbacks = function() {
for ( var i = 0; i < complex.length; i++ ) {
var name = complex[i]['feedback_name'];
var desc = complex[i]['feedback_text'];
}
var i = 0;
var fnchange = function() {
$('#footerfeedbackItemContent').animate({'opacity': 0}, 2000, function () {
$(this).text(desc);
}).animate({'opacity': 1}, 2500);
$('#footerfeedbackItemCustomer').animate({'opacity': 0}, 2000, function () {
$(this).text(name);
}).animate({'opacity': 1}, 2500);
if( ++i < json.length ){
setTimeout(fnchange, 10000);
} else {
i = 0;
setTimeout(fnchange, 10000);
}
};
setTimeout(fnchange, 1);
};
setTimeout(feedbacks,1);
});

Categories