Play audio file based on id from mysql database - javascript

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
});
});

Related

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>
`;

Draw in two tables vanilla JS

I am working with program that will randomly choose who is making a Christmas gift to whom.
I've created an empty array. When you add a "player" it's pushing the name into two different arrays. Players[] and Players2[].
When you start a draw. The program writes the names of the Players[] on the left hand side and on the right side it writes the drawn names from Players2[].
Every Player from Players2[], after being drawn, is being deleted from the array so in the end we have an empty Players2[] array and full Players[] array.
The problem is: I can't make a working if statement that is checking if the person will not draw himself...
let Players = [];
let Players2 = [];
const addBTN = document.getElementById('addBTN');
const onlyLetters = /^[a-zżźćóęśńłA-ZŻŹĆÓŁĘŚŃŁ ]+$/;
const refreshBTN = document.getElementById('refreshBTN');
const warningBTNyes = document.getElementById('warning-button-yes');
const warningBTNno = document.getElementById('warning-button-no');
const playersList = document.getElementById('playersList');
const playersList2 = document.getElementById('playersList2');
const startBTN = document.getElementById('startBTN');
const drawLotsBTN = document.getElementById('drawLotsBTN');
addBTN.addEventListener('click', function() {
const input = document.getElementById('addPLAYER');
const person = document.getElementById('addPLAYER').value;
if (input.value == "") {
console.log('error_empty_input');
document.getElementById('errorMSG').style.color = "red";
document.getElementById('errorMSG').innerHTML = "Wpisz imię osoby!";
} else if (input.value.match(onlyLetters)) {
console.log('good');
Players.push(person);
Players2.push(person);
playersList.innerHTML = playersList.innerHTML + "<br>" + person;
document.getElementById('addPLAYER').value = "";
document.getElementById('errorMSG').style.color = "green";
document.getElementById('errorMSG').innerHTML = "Powodzenie! Dodaj kolejną osobę.";
} else {
console.log('error_input');
document.getElementById('errorMSG').style.color = "red";
document.getElementById('errorMSG').innerHTML = "Coś jest nie tak z imieniem. Pamiętaj aby wprowadzać same litery!";
}
});
refreshBTN.addEventListener('click', function() {
document.getElementById('warning').style.display = "block";
});
warningBTNyes.addEventListener('click', function() {
location.reload(true);
document.getElementById('addPLAYER').value = "";
});
warningBTNno.addEventListener('click', function() {
document.getElementById('warning').style.display = "none";
});
startBTN.addEventListener('click', function() {
drawLotsBTN.disabled = false;
const input = document.getElementById('addPLAYER');
const person = document.getElementById('addPLAYER').value;
if (input.value == "") {
} else if (input.value.match(onlyLetters)) {
console.log('good');
Players.push(person);
Players2.push(person);
playersList.innerHTML = playersList.innerHTML + "<br>" + person;
document.getElementById('addPLAYER').value = "";
document.getElementById('errorMSG').style.color = "green";
document.getElementById('errorMSG').innerHTML = "Powodzenie! Zaczynasz losowanie!";
} else {
console.log('error_input');
document.getElementById('errorMSG').style.color = "red";
document.getElementById('errorMSG').innerHTML = "Coś jest nie tak z imieniem. Pamiętaj aby wprowadzać same litery!";
}
document.getElementById('addPLAYER').disabled = true;
});
drawLotsBTN.addEventListener('click', function() {
for (let i = 0; i = Players2.length; i++) {
if (Players2.length > 0) {
randomPerson = Math.floor(Math.random() * Players2.length);
if (randomPerson != Players.indexOf(i)) {
console.log(Players2[randomPerson]);
playersList2.innerHTML = playersList2.innerHTML + "<br>" + Players2[randomPerson];
Players2.splice(randomPerson, 1);
}
} else {
console.log('error_empty_array');
}
}
});
<div id="warning" class="warning">
<div class="warning-flex">
<h1>Wszelkie wpisane imiona zostaną usunięte</h1>
<div class="warning-buttons">
<button id="warning-button-yes" class="warning-button-yes">Tak</button>
<button id="warning-button-no" class="warning-button no">Nie</button>
</div>
</div>
</div>
<div class="lotteryContainer">
<div class="left">
<p>dodaj osobę</p>
<div class="addPerson">
<input required id="addPLAYER" type="text">
<button id="addBTN">+</button>
<p id="errorMSG"></p>
<div class="refresh">
<button id="refreshBTN">Od nowa</button>
<button id="startBTN">Start</button>
</div>
</div>
</div>
<div class="right">
<p>Uczestnicy</p>
<div class="tables">
<div class="tableLeft">
<p id=playersList></p>
</div>
<div class="tableRight">
<p id="playersList2"></p>
</div>
</div>
<button id="drawLotsBTN">Losuj</button>
</div>
</div>
<script src="app.js"></script>
Now if I understand what your program aims to do, there is a simple algorithm for it.
How I understand your goal:
You have a list of persons who are going to give presents to each other. (like in secret Santa). It is random who will give to who, but each person gives and receives one gift.
How to implement it (i'd normaly use maps, but I am guessing you are more comfortable with arrays):
players = ["Adam", "Bret", "Clay", "Donald"];
players.sort(function(a, b){return 0.5 - Math.random()}); // shuffles array
gives_to = [...players]; // copy values of array
gives_to.push(gives_to.shift()); // let the first element be the last
Here the first player (players[0]) will give to gives_to[0] and the second to gives_to[1] etc.
I've created this JS script trying to use Trygve Ruud algorithm but it doesn't work like desired.
drawLotsBTN.addEventListener('click', function(){
if(Players.length > 0) {
console.log(Players)
Players.sort(function(a, b){
return 0.5 - Math.random();
});
for(let i = 0; i < Players.length; i++){
playersList2.innerHTML = playersList2.innerHTML + "<br>" + Players[i];
}
}
else{
console.log('error_empty_array');
}
});

How to make multiple html elements use the same Javascript without copying code and changing variables?

I apologize if the title isn't clear, I created a simple audio player with html and java, is there a way to put multiple of these on my website without the need to rewrite all the variables, IDs and stuff?
I think I'd need to use classes, but I don't really have much knowledge about OOP, so any help is appreciated.
Here's my html:
<body>
<div id="wrapper">
<fieldset>
<legend>Song</legend>
<div id='player'>
<audio id="music_player" preload="metadata" loop>
<source src="music\song.mp3">
</audio>
<input type="image" src="images/playButton.png" onclick="play_aud()" id="play_button">
<input type="image" src="images/pauseButton.png" onclick="pause_aud()" id="play_button">
<input type="image" src="images/stopButton.png" onclick="stop_aud()" id="play_button">
<span id="current-time" class="time">0:00</span>
<input type="range" id="seek-slider" max="100" value="0">
<span id="duration" class="time">0:00</span>
<input type="image" src="images/volumeButton.png" id="vol_img" onclick="mute()">
<input type="range" id="change_vol" onchange="change_vol()" step="0.05" min="0" max="1" value="1">
</div>
</fieldset>
</div>
</body>
<script src="script.js"></script>
And Javascript:
let muteState = 'unmute';
var player;
const audioButton = document.getElementById('vol-img');
const currentTimeContainer = document.getElementById('current-time');
const audio = document.querySelector('audio');
const durationContainer = document.getElementById('duration');
const seekSlider = document.getElementById('seek-slider')
const calculateTime = (secs) => {
const minutes = Math.floor(secs / 60);
const seconds = Math.floor(secs % 60);
const returnedSeconds = seconds < 10 ? `0${seconds}` : `${seconds}`;
return `${minutes}:${returnedSeconds}`;
}
const displayDuration = () => {
durationContainer.textContent = calculateTime(audio.duration);
}
const setSliderMax = () => {
seekSlider.max = Math.floor(audio.duration);
}
const displayBufferedAmount = () => {
const bufferedAmount = Math.floor(audio.buffered.end(audio.buffered.length - 1));
audioPlayerContainer.style.setProperty('--buffered-width', `${(bufferedAmount / seekSlider.max) * 100}%`);
}
function startplayer()
{
player = document.getElementById('music_player');
player.controls = false;
}
function play_aud()
{
player.play();
}
function pause_aud()
{
player.pause();
}
function stop_aud()
{
player.pause();
player.currentTime = 0;
}
function change_vol()
{
player.volume=document.getElementById("change_vol").value;
}
function mute()
{
if(muteState == 'mute')
{
document.getElementById('vol_img').src = 'images/volumeButton.png';
muteState = 'unmute';
audio.muted = false;
}
else
{
document.getElementById('vol_img').src = 'images/volumeButtonmute.png';
muteState = 'mute'
audio.muted = true;
}
};
if (audio.readyState > 0) {
displayDuration();
setSliderMax();
displayBufferedAmount();
} else {
audio.addEventListener('loadedmetadata', () => {
displayDuration();
setSliderMax();
displayBufferedAmount();
});
}
audio.addEventListener('progress', displayBufferedAmount);
seekSlider.addEventListener('input', () => {
currentTimeContainer.textContent = calculateTime(seekSlider.value);
});
seekSlider.addEventListener('change', () => {
audio.currentTime = seekSlider.value;
});
audio.addEventListener('timeupdate', () => {
seekSlider.value = Math.floor(audio.currentTime);
currentTimeContainer.textContent = calculateTime(audio.currentTime);
});
i have converted all code to class based so now you can create as many instances as you want
i have changed all getElementById to querySelector since its more suitable for this situation
class audio_player{
constructor(root){
this.html = `
<div id="wrapper">
<fieldset>
<legend>Song</legend>
<div id='player'>
<audio id="music_player" preload="metadata" loop>
<source src="music\song.mp3">
</audio>
<input type="image" src="images/playButton.png" onclick="play_aud()" id="play_button">
<input type="image" src="images/pauseButton.png" onclick="pause_aud()" id="play_button">
<input type="image" src="images/stopButton.png" onclick="stop_aud()" id="play_button">
<span id="current-time" class="time">0:00</span>
<input type="range" id="seek-slider" max="100" value="0">
<span id="duration" class="time">0:00</span>
<input type="image" src="images/volumeButton.png" id="vol_img" onclick="mute()">
<input type="range" id="change_vol" onchange="change_vol()" step="0.05" min="0" max="1" value="1">
</div>
</fieldset>
</div>
`
root.innerHTML = this.html
this.html = root
this.interactivity()
}
interactivity(){
let muteState = 'unmute';
var player;
const audioButton = this.html.querySelector('#vol-img');
const currentTimeContainer = this.html.querySelector('#current-time');
const audio = this.html.querySelector('audio');
const durationContainer = this.html.querySelector('#duration');
const seekSlider = this.html.querySelector('#seek-slider')
const calculateTime = (secs) => {
const minutes = Math.floor(secs / 60);
const seconds = Math.floor(secs % 60);
const returnedSeconds = seconds < 10 ? `0${seconds}` : `${seconds}`;
return `${minutes}:${returnedSeconds}`;
}
const displayDuration = () => {
durationContainer.textContent = calculateTime(audio.duration);
}
const setSliderMax = () => {
seekSlider.max = Math.floor(audio.duration);
}
const displayBufferedAmount = () => {
const bufferedAmount = Math.floor(audio.buffered.end(audio.buffered.length - 1));
audioPlayerContainer.style.setProperty('--buffered-width', `${(bufferedAmount / seekSlider.max) * 100}%`);
}
function startplayer()
{
player = this.html.querySelector('#music_player');
player.controls = false;
}
function play_aud()
{
player.play();
}
function pause_aud()
{
player.pause();
}
function stop_aud()
{
player.pause();
player.currentTime = 0;
}
function change_vol()
{
player.volume=this.html.querySelector("#change_vol").value;
}
function mute()
{
if(muteState == 'mute')
{
this.html.querySelector('#vol_img').src = 'images/volumeButton.png';
muteState = 'unmute';
audio.muted = false;
}
else
{
this.html.querySelector('#vol_img').src = 'images/volumeButtonmute.png';
muteState = 'mute'
audio.muted = true;
}
};
if (audio.readyState > 0) {
displayDuration();
setSliderMax();
displayBufferedAmount();
} else {
audio.addEventListener('loadedmetadata', () => {
displayDuration();
setSliderMax();
displayBufferedAmount();
});
}
audio.addEventListener('progress', displayBufferedAmount);
seekSlider.addEventListener('input', () => {
currentTimeContainer.textContent = calculateTime(seekSlider.value);
});
seekSlider.addEventListener('change', () => {
audio.currentTime = seekSlider.value;
});
audio.addEventListener('timeupdate', () => {
seekSlider.value = Math.floor(audio.currentTime);
currentTimeContainer.textContent = calculateTime(audio.currentTime);
});
}
}
const newAudio1 = new audio_player(document.querySelector(".player1"))
const newAudio2 = new audio_player(document.querySelector(".player2"))
const newAudio3 = new audio_player(document.querySelector(".player3"))
<div class="player1"></div>
<div class="player2"></div>
<div class="player3"></div>

comment appending on the first post only in Vanilla JavaScript

I am creating a status posting and commenting system.
It is implemented in Vanilla JavaScript. Anyone can add a post and can comment on the post.
Everything is working fine but the comment section is working on first post only.
deletion of comment and post is working fine.
I don't know what's the problem is, if anyone could help me..
Here is the HTML code
<div class="container-post" id="container-post">
<div class="create-post">
<form>
<div class="form-group">
<div class="username">
<p class="name" style="top:15px;">User Name</p>
</div>
<p class="qoutes">
<textarea style=" font-size: 15pt;" class="form-control" id="enter-post" rows="7" id="mypara" placeholder="Share Your Thoughts..."></textarea>
</p>
<div class="postbar">
<button type="button" class="btn btn-primary post-me" id="post-button"> <span id="postText">Post</span></button>
</div>
</div>
</form>
</div>
<hr class="line-bar">
<div class="allpost">
<div class="mainpost" id="post-div"></div>
</div>
Here is the JavaSCript code
showTask();
showComment();
let addPost = document.getElementById("enter-post");
let addPostBtton = document.getElementById("post-button");
addPostBtton.addEventListener("click", function () {
var addPostVal = addPost.value;
if (addPostVal.trim() != 0) {
let webtask = localStorage.getItem("localtask");
if (webtask == null) {
var taskObj = [];
}
else {
taskObj = JSON.parse(webtask);
}
taskObj.push(addPostVal);
localStorage.setItem("localtask", JSON.stringify(taskObj));
}
showTask();
});
function showTask() {
let webtask = localStorage.getItem("localtask");
if (webtask == null) {
var taskObj = [];
}
else {
taskObj = JSON.parse(webtask);
}
let htmlVal = '';
let createPost = document.getElementById("post-div");
taskObj.forEach((item, index) => {
htmlVal += `
<div class="post-class"><div class="username u-name">
<p class="name i-name">${"User Name " + index}</p>
<i class="fas fa-trash-alt" onclick="removePost(${index});"></i></button>
</div>
<hr>
<p class="quotes">
${item}
</p>
<div class="comment-section" id="comment-section">
<p class="comment-qoute">
<textarea style=" font-size: 15pt;" class="form-control commentBox" rows="3" id="mypara" placeholder="Leave a comment"></textarea>
</p>
<button class="btn btn-primary comment-btn" id="commentBtn">comment</button>
<ul class="comments" id="comments-portion">
<p></p>
</ul>
</div>
</div>
<br><br>`
});
createPost.innerHTML = htmlVal;
}
function removePost(index) {
let webtask = localStorage.getItem("localtask");
let taskObj = JSON.parse(webtask);
taskObj.splice(index, 1);
localStorage.setItem("localtask", JSON.stringify(taskObj));
showTask();
}
var commentPost = document.getElementById('mypara');
var commentBtn = document.getElementById('commentBtn');
commentBtn.addEventListener('click', function () {
var commentValue = commentPost.value;
if (commentValue.trim() != 0) {
let commentTask = localStorage.getItem("comments");
if (commentTask == null) {
var commentObj = [];
}
else {
commentObj = JSON.parse(commentTask);
}
commentObj.push(commentValue);
localStorage.setItem("comments", JSON.stringify(commentObj));
}
showComment();
});
function showComment() {
let commentsTask = localStorage.getItem("comments");
if (commentsTask == null) {
var commentObj = [];
}
else {
commentObj = JSON.parse(commentsTask);
}
let commentHTMLValue = '';
var createComment = document.getElementById("comments-portion");
commentObj.forEach((item, index) => {
commentHTMLValue += `<div class="comment-box-btn">
<p>${index + ". "}<span>${item}</span></p>
<i class="far fa-times-circle fa-2x" onclick="removeComment(${index});"></i>
</div>
`;
});
createComment.innerHTML = commentHTMLValue;
}
var deleteBtn = document.querySelector('.comment-del');
deleteBtn.addEventListener('click', () => {
});
// remove comment
function removeComment(index) {
let commentTask = localStorage.getItem("comments");
let commentObj = JSON.parse(commentTask);
commentObj.splice(index, 1);
localStorage.setItem("comments", JSON.stringify(commentObj));
showComment();
}
When you use code like:
createComment.innerHTML = commentHTMLValue;
you are completely replacing the contents of the element. Try using:
createComment.innerHTML += commentHTMLValue;
which appends new content to the end of the existing contents.
I can't do a snippet here as the use of localStorage is not allowed. Copy this block into a blank file and save it as an html file and then open that in a browser.
This is how I think you are describing your requirements and is also based on the data format in my comments. It's not pretty and needs plenty of sprucing up, but it runs.
<!DOCTYPE html>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
<html>
<head>
<title>Task listing</title>
<script type="text/javascript">
let taskList = [];
function checkTasks() {
let tasksList = getTasksList();
if (tasksList.length == 0) {
let newTask = prompt("Please enter a task description");
if (newTask) {
let thisIndex = getNewIndex();
let a = {"id": thisIndex, "task": newTask, "comments": []}
taskList.push(a);
saveTasksList(taskList);
}
}
displayTasks();
}
function displayTasks() {
let container = document.getElementById("tasks");
container.innerHTML = "";
let taskList = getTasksList();
taskList.forEach(function(task){
let d = document.createElement("div");
d.id = "task_" + task.id;
d.className = "commentdiv";
d.innerHTML = "<h3>" + task.task + "</h3>";
let l = document.createElement("ul");
l.id = "comments_" + task.id;
let comments = task.comments;
if (comments.length > 0) {
let commentindex = 0;
comments.forEach(function(comment) {
let c = document.createElement("li");
c.innerHTML = comment;
let cb = document.createElement("button");
cb.id = "deletecomment_" + task.id + "_" + commentindex;
cb.innerHTML = "Delete comment";
cb.onclick = function() {deleteComment(task.id, commentindex);};
c.appendChild(cb);
l.appendChild(c);
})
}
let b = document.createElement("button");
b.id = "addcomment_" + task.id;
b.onclick = function() {addComment(task.id);};
b.innerHTML = "Add comment";
d.appendChild(b);
d.appendChild(l);
container.appendChild(d);
})
}
function addComment(taskid) {
let newcomment = prompt("Enter comment");
if (newcomment) {
let tasklist = getTasksList();
let filtered = tasklist.filter(task => task.id == taskid);
if (filtered[0]) {
let thisTask = filtered[0];
thisTask.comments.push(newcomment);
let thisIndex = taskList.findIndex((task) => task.id == taskid);
taskList[thisIndex] = thisTask;
}
saveTasksList(taskList);
displayTasks();
}
}
function addNewTask() {
let newTask = prompt("Enter task description");
let taskList = getTasksList();
let lastindex = localStorage.getItem("tasksindex");
let index = getNewIndex();
let a = {"id": index, "task": newTask, "comments": []}
taskList.push(a);
saveTasksList(taskList);
displayTasks();
}
function deleteComment(taskid, commentindex) {
let tasklist = getTasksList();
let filtered = tasklist.filter(task => task.id == taskid);
// as long as there is at least one task with the taskid value, find and delete the comment
// based on the index position of the comment in the comments array
if (filtered[0]) {
let thisTask = filtered[0];
thisTask.comments.splice(commentindex, 1);
let thisIndex = taskList.findIndex((task) => task.id == taskid);
taskList[thisIndex] = thisTask;
}
saveTasksList(taskList);
displayTasks();
}
function getTasksList() {
let tasks = localStorage.getItem("tasks");
taskList = JSON.parse(tasks);
if (!taskList) {
taskList = [];
}
return taskList;
}
function saveTasksList(taskList) {
localStorage.setItem("tasks", JSON.stringify(taskList));
}
function getNewIndex() {
let lastindex = localStorage.getItem("tasksindex");
let idx = 0;
if (!lastindex) {
idx = 1;
} else {
idx = Number(lastindex) + 1;
}
localStorage.setItem("tasksindex", idx);
return idx;
}
function removeAll() {
localStorage.removeItem("tasks");
localStorage.removeItem("tasksindex");
displayTasks();
}
window.onload = checkTasks;
</script>
<style type="text/css">
.commentdiv {
border:1px solid black;
width:1000px;
padding:5px;
border-radius:5px;
}
button {
margin-left:10px;
}
h3 {
width:100%;
border-bottom: 1px dotted black;
}
ul {
list-style-type:decimal;
}
</style>
</head>
<body>
<h2>My task list <button id="addNewTaskButton" onclick="addNewTask();">Add new task</button></h2>
<hr>
<div id="tasks">
</div>
<button id="removeAll" onclick="removeAll();">Remove all tasks</button>
</body>
</html>

Toggle to open/close tabbed navigation

I am very new to jQuery/Javascript and have been trying to have a tabbed navigation menu closed on page load then open if clicked by the user. So far I haven't had any joy with editing the following file
function amshopby_start(){
$$('.block-layered-nav .form-button').each(function (e){
e.observe('click', amshopby_price_click_callback);
});
$$('.block-layered-nav .input-text').each(function (e){
e.observe('focus', amshopby_price_focus_callback);
e.observe('keypress', amshopby_price_click_callback);
});
$$('a.amshopby-more', 'a.amshopby-less').each(function (a){
a.observe('click', amshopby_toggle);
});
$$('span.amshopby-plusminus').each(function (span){
span.observe('click', amshopby_category_show);
});
$$('.block-layered-nav dt').each(function (dt){
dt.observe('click', amshopby_filter_show);
});
$$('.block-layered-nav dt img').each(function (img){
img.observe('mouseover', amshopby_tooltip_show);
img.observe('mouseout', amshopby_tooltip_hide);
});
$$('.amshopby-slider-param').each(function (item) {
param = item.value.split(',');
amshopby_slider(param[0], param[1], param[2], param[3], param[4], param[5], param[6]);
});
}
function amshopby_price_click_callback(evt) {
if (evt && evt.type == 'keypress' && 13 != evt.keyCode)
return;
var prefix = 'amshopby-price';
// from slider
if (typeof(evt) == 'string'){
prefix = evt;
}
else {
var el = Event.findElement(evt, 'input');
if (!Object.isElement(el)){
el = Event.findElement(evt, 'button');
}
prefix = el.name;
}
var a = prefix + '-from';
var b = prefix + '-to';
var numFrom = amshopby_price_format($(a).value);
var numTo = amshopby_price_format($(b).value);
if ((numFrom < 0.01 && numTo < 0.01) || numFrom < 0 || numTo < 0) {
return;
}
var url = $(prefix +'-url').value.gsub(a, numFrom).gsub(b, numTo);
amshopby_set_location(url);
}
function amshopby_price_focus_callback(evt){
var el = Event.findElement(evt, 'input');
if (isNaN(parseFloat(el.value))){
el.value = '';
}
}
function amshopby_price_format(num){
num = parseFloat(num);
if (isNaN(num))
num = 0;
return Math.round(num);
}
function amshopby_slider(width, from, to, max_value, prefix, min_value, ratePP) {
width = parseFloat(width);
from = parseFloat(from);
to = parseFloat(to);
max_value = parseFloat(max_value);
min_value = parseFloat(min_value);
var slider = $(prefix);
// var allowedVals = new Array(11);
// for (var i=0; i<allowedVals.length; ++i){
// allowedVals[i] = Math.round(i * to /10);
// }
return new Control.Slider(slider.select('.handle'), slider, {
range: $R(0, width),
sliderValue: [from, to],
restricted: true,
//values: allowedVals,
onChange: function (values){
this.onSlide(values);
amshopby_price_click_callback(prefix);
},
onSlide: function(values) {
var fromValue = Math.round(min_value + ratePP * values[0]);
var toValue = Math.round(min_value + ratePP * values[1]);
/*
* Change current selection style
*/
if ($(prefix + '-slider-bar')) {
var barWidth = values[1] - values[0] - 1;
if (values[1] == values[0]) {
barWidth = 0;
}
$(prefix + '-slider-bar').setStyle({
width : barWidth + 'px',
left : values[0] + 'px'
});
}
if ($(prefix+'-from')) {
$(prefix+'-from').value = fromValue;
$(prefix+'-to').value = toValue;
}
if ($(prefix + '-from-slider')) {
$(prefix + '-from-slider').update(fromValue);
$(prefix + '-to-slider').update(toValue);
}
}
});
}
function amshopby_toggle(evt){
var attr = Event.findElement(evt, 'a').id.substr(14);
$$('.amshopby-attr-' + attr).invoke('toggle');
$('amshopby-more-' + attr, 'amshopby-less-' + attr).invoke('toggle');
Event.stop(evt);
return false;
}
function amshopby_category_show(evt){
var span = Event.findElement(evt, 'span');
var id = span.id.substr(16);
$$('.amshopby-cat-parentid-' + id).invoke('toggle');
span.toggleClassName('minus');
Event.stop(evt);
return false;
}
function amshopby_filter_show(evt){
var dt = Event.findElement(evt, 'dt');
dt.next('dd').down('ol').toggle();
dt.toggleClassName('amshopby-collapsed');
Event.stop(evt);
return true;
}
function amshopby_tooltip_show(evt){
var img = Event.findElement(evt, 'img');
var txt = img.alt;
var tooltip = $(img.id + '-tooltip');
if (!tooltip) {
tooltip = document.createElement('div');
tooltip.className = 'amshopby-tooltip';
tooltip.id = img.id + '-tooltip';
tooltip.innerHTML = img.alt;
document.body.appendChild(tooltip);
}
var offset = Element.cumulativeOffset(img);
tooltip.style.top = offset[1] + 'px';
tooltip.style.left = (offset[0] + 30) + 'px';
tooltip.show();
}
function amshopby_tooltip_hide(evt){
var img = Event.findElement(evt, 'img');
var tooltip = $(img.id + '-tooltip');
if (tooltip) {
tooltip.hide();
}
}
function amshopby_set_location(url){
if (typeof amshopby_working != 'undefined'){
return amshopby_ajax_request(url);
}
else {
return setLocation(url);
}
}
document.observe("dom:loaded", function() { amshopby_start(); });
The element that I am trying to manipulate is contained in this file
<?php if($this->canShowBlock()): ?>
<div class="block block-layered-nav">
<div class="block-title">
<strong><span><?php echo $this->__('Shop By') ?></span></strong>
</div>
<?php echo $this->getStateHtml() ?>
<div class="block-content">
<?php if($this->canShowOptions()): ?>
<!-- <p class="block-subtitle">--><?php //echo $this->__('Shopping Options') ?><!--</p>-->
<ul id="narrow-by-list">
<li>
<?php $_filters = $this->getFilters() ?>
<?php foreach ($_filters as $_filter): ?>
<?php if($_filter->getItemsCount()): ?>
<div class="opt-row">
<dl class="opt-row">
<dt><?php echo $this->__($_filter->getName()) ?></dt>
<dd><?php echo $_filter->getHtml() ?></dd>
</dl>
</div>
<?php endif; ?>
<?php endforeach; ?>
</li>
</ul>
<script type="text/javascript">decorateDataList('narrow-by-list')</script>
<?php endif; ?>
<?php if ($this->getLayer()->getState()->getFilters()): ?>
<div class="actions"><?php echo $this->__('Clear All') ?></div>
<?php endif; ?>
</div>
</div>
<?php endif; ?>
When the page loads I woul like to have the tabbed navigation menus closed but toggable to open by the user... Can anyone assist please?
From the admin panel, you can make any of your filters closed by default:-
Catalog > Improved Navigation > Filters
Select the relevant filter and set 'Collapsed' to 'Yes'.

Categories