Object value can't be read in my todoList - javascript

I made a TODO list where you can type in something you have to do. When you click on save, the system will add it as a todo-item. When I click on the V the todo item will change to a done item but it can't read the value of it.
How can I fix this? What did I wrong so the code doesn't read the input value?
const $textArea = document.getElementById("todo-input");
const $saveBtn = document.getElementById("save-btn");
const $todoList = document.getElementById("todo-list");
const $todoCount = document.getElementById("todo-count");
const $doneList = document.getElementById("done-list");
const $doneCount = document.getElementById("done-count");
const $clearAllBtn = document.getElementById("clear-all-btn");
const state = {
focusIndex: NaN,
todoList: [],
doneList: [],
};
function setState() {
fetch("https://phpstack-224488-1624928.cloudwaysapps.com/_/items/todo?filter%5Bdone%5D%5Beq%5D=0", {
method: "GET",
headers: {
Authorization: "bearer ABcEHA2kcrKY4a6ipUA3",
},
}).then((response) => {
if (!response.ok) {
throw new Error("could not fetch todoItems");
}
return response.json();
}).then(function(body) {
state.todoList = body.data;
printTodoList();
}).catch((err) => {
console.error(err);
});
}
function printTodoList() {
$todoList.innerHTML = "";
let template = "";
for (let i = 0; i <
state.todoList.length; i++) {
template += ` <div class="box ${
i === state.focusIndex ? " active " : " "
}" data-index="${i}">
<p>${state.todoList[i].description}</p>
<a class="done-btn fas fa-check-circle fa-2x"></a>
</div>`;
}
$todoList.insertAdjacentHTML("beforeend", template);
$todoCount.innerText = state.todoList.length;
}
function printDoneList() {
$doneList.innerHTML = "";
let template = "";
for (let i = 0; i <
state.doneList.length; i++) {
template += ` <div class="box">
<p>${state.doneList[i]}</p>
<a class="remove-btn fas fa-times-circle fa-2x" data-index="${i}"></a>
</div>`;
}
$doneList.insertAdjacentHTML("beforeend", template);
$doneCount.innerText = state.doneList.length;
console.log($doneList);
}
function saveBtnClicked() {
const body = {
description: $textArea.value,
done: false,
};
fetch("https://phpstack-224488-1624928.cloudwaysapps.com/_/items/todo", {
method: "POST",
headers: {
Authorization: "bearer ABcEHA2kcrKY4a6ipUA3",
"Content-Type": "application/json",
},
body: JSON.stringify(body),
}).then((response) => {
if (!response.ok) {
throw new Error("could not save todoItem");
}
return response.json();
}).then(function(body) {
state.todoList.push(body.data);
printTodoList();
}).catch((err) => {
console.error(err);
});
}
function todoListClicked(event) {
const $target = event.target;
if ($target.matches(".done-btn")) {
const curIndex = $target.closest(".box").dataset.index;
const doneItem = state.todoList.splice(curIndex, 1);
state.doneList.push(doneItem[0]); // state.doneList = state.doneList.concat(doneItem); // alternatief printTodoList(); printDoneList(); } if ($target.matches(".box") || $target.matches(".box p"))
{
const curIndex = parseInt($target.closest(".box").dataset.index);
state.focusIndex = curIndex === state.focusIndex ? NaN : curIndex;
printTodoList();
}
}
function doneListClicked(event) {
const $target = event.target;
if ($target.matches(".remove-btn")) {
const curIndex = $target.dataset.index;
state.doneList.splice(curIndex, 1);
printDoneList();
}
}
function clearAllBtnClicked() {
state.todoList = [];
state.doneList = [];
printTodoList();
printDoneList();
}
$saveBtn.addEventListener("click", saveBtnClicked);
$todoList.addEventListener("click", todoListClicked);
$doneList.addEventListener("click", doneListClicked);
$clearAllBtn.addEventListener("click", clearAllBtnClicked);
printDoneList();
setState();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>TODO or not TODO</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.2/css/bulma.min.css" />
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.5.0/css/all.css" integrity="sha384-B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU" crossorigin="anonymous" />
<link rel="stylesheet" href="style.css" />
</head>
<body>
<section class="hero is-primary">
<div class="hero-body">
<div class="container">
<h1 class="title">TODO or not TODO</h1>
</div>
</div>
</section>
<div class="container">
<section class="section">
<div id="input-container">
<div class="field">
<div class="control">
<textarea id="todo-input" class="textarea is-success" placeholder="What to do?"></textarea>
</div>
</div>
<div class="field is-grouped">
<p class="control is-expanded">
<button id="save-btn" class="button is-success is-fullwidth">
Save
</button>
</p>
<p class="control">
<button id="clear-all-btn" class="button is-danger">
Clear All
</button>
</p>
</div>
</div>
</section>
<section class="count-container">
Todo: <span id="todo-count">5</span>
</section>
<section id="todo-list" class="section no-top-padding">
<div class="box active">
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus ad aliquam debitis dolores eos excepturi iusto libero, magnam nulla pariatur provident quibusdam quod, repellendus. A illum laudantium quas reprehenderit voluptas?
</p>
<a class="done-btn fas fa-check-circle fa-2x"></a>
</div>
<div class="box">
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus ad aliquam debitis dolores eos excepturi iusto libero, magnam nulla pariatur provident quibusdam quod, repellendus. A illum laudantium quas reprehenderit voluptas?
</p>
<a class="done-btn fas fa-check-circle fa-2x"></a>
</div>
<div class="box">
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus ad aliquam debitis dolores eos excepturi iusto libero, magnam nulla pariatur provident quibusdam quod, repellendus. A illum laudantium quas reprehenderit voluptas?
</p>
<a class="done-btn fas fa-check-circle fa-2x"></a>
</div>
</section>
<section class="count-container">
Done: <span id="done-count">5</span>
</section>
<section id="done-list" class="section no-top-padding">
<div class="box">
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus ad aliquam debitis dolores eos excepturi iusto libero, magnam nulla pariatur provident quibusdam quod, repellendus. A illum laudantium quas reprehenderit voluptas?
</p>
<a class="remove-btn fas fa-times-circle fa-2x"></a>
</div>
</section>
</div>
<script src="script.js"></script>
</body>
</html>

Related

Using one function for multiple html classes in javascript (expanding text via read more button)

First post on stack overflow:)
I'm trying to put one certain function on all of my HTML-buttons, so far I haven't found anything that worked after 2 days of trying out(new to coding).
What I'm basically trying to do is a 'read more' button that displays a text on click. Neither .getElementsByClassName nor .querySelectorAll have worked so far. If I use my code with just an #id it works fine, but I know there must be a better way of using one function for multiple elements instead of having multiple ids and using the function for each id individually . I've also tried a forEach() loop but it didn't do anything. Additionally I've tried readMoreBtn[length].addEventListener('click', () => {}), but that also didn't work.
As I said, it works with the .getElementById and querySelector, but not with .getElementsByClassName or .querySelectorAll. If I use querySelectorAll, the first button works but the others don't.
Since I'm interested in making it work with classes and not ids, I've removed the id-attributes from the HTML.
I won't post my full HTML since it's quite long but the container with the button looks like the following:
<div class="main-container">
<h6 class="main-artist"><em class="main-emph">content</em>content</h6>
<p class="main-p"><span class="moreText"> Lorem ipsum </span></p>
<button class="readMore">read more</button>
</div>
And JS:
const readMoreBtn = document.getElementsByClassName('.readMore');
const text = document.querySelector('.main-p');
readMoreBtn.addEventListener('click', () => {
text.classList.toggle('show-more');
if(readMoreBtn.innerHTML === "read more") {
readMoreBtn.innerHTML = "read less"
} else {
readMoreBtn.innerHTML = "read more"
}
})
Thank you for your help and if you have any suggestions of how to improve my way of asking questions, shoot.
EDIT: I have multiple buttons, and all of them have a unique text. My goal is it to have the buttons display their unique text below them somehow. Here's another HTML to show what I mean:
<div class="main-container">
<h6 class="main-artist"><em class="main-emph">content</em>content</h6>
<p class="main-p"><span class="moreText"> Lorem ipsum </span></p>
<button class="readMore">read more</button>
</div>
<div class="main-container">
<h6 class="main-artist"><em class="main-emph">content</em>content</h6>
<p class="main-p"><span class="moreText"> Messi GOAT </span></p>
<button class="readMore">read more</button>
</div>
<div class="main-container">
<h6 class="main-artist"><em class="main-emph">content</em>content</h6>
<p class="main-p"><span class="moreText"> Ipsum Lorem </span></p>
<button class="readMore">read more</button>
</div>
With this JS Code I'm able to expand the first main-p only, but not the others.
const yourFunction = (e)=>{
const text = document.querySelector('.main-p');
text.classList.toggle('show-more');
if(e.target.innerHTML === "read more") {
e.target.innerHTML = "read less"
} else {
e.target.innerHTML = "read more"
}
}
In my head there are two solutions that might work:
I would have to connect each button to their main-p somehow in HTML? I've tried it but it didn't work.
Working with loops in JS.
Is one of those two possible? TIA
There are many ways to do this.
Try this one.
const yourFunction = (e) => {
const text = document.querySelector('.main-p');
text.classList.toggle('show-more');
if (e.target.innerHTML === "read more") {
e.target.innerHTML = "read less"
} else {
e.target.innerHTML = "read more"
}
}
<div class="main-container">
<h6 class="main-artist"><em class="main-emph">content</em>content</h6>
<p class="main-p"><span class="moreText"> Lorem ipsum </span></p>
<button class="readMore" onclick="yourFunction(event)">read more</button>
</div>
getElementsByClassName() returns an HTMLCollection.
And querySelectorAll() returns a NodeList.
By contrast querySelector() and getElementById() return a DOM Element.
Each of these types are accessed and manipulated differently. You are treating the HTMLCollection and the NodeList as an Element.
One way to access every item in an HTMLCollection and NodeList is to first convert them to an array using Array.from(), then use forEach() on the resulting array to iterate each Element, in this case adding a click event handler to the element:
const readMoreBtn = document.getElementsByClassName('readMore');
const text = document.querySelectorAll('.main-p');
console.log(Array.from(text));
Array.from(readMoreBtn).forEach(function(elem) {
elem.addEventListener('click', ({target}) => {
target.textContent = ('read more' === target.textContent) ? 'read less' : 'read more';
});
});
<p class="main-p"><span class="moreText"> Lorem ipsum 1</span></p>
<button class="readMore">read more</button>
<p class="main-p"><span class="moreText"> Lorem ipsum 2</span></p>
<button class="readMore">read more</button>
<p class="main-p"><span class="moreText"> Lorem ipsum 3</span></p>
<button class="readMore">read more</button>
I prefer to use less JS, but more CSS. (more flexible)
Example, just add .is-acitve in container (parent) so just styling in CSS
const buttons = document.querySelectorAll('.main-container .readMore');
const setContainerActive = (el) => {
el.target.closest('.main-container').classList.toggle('is-active')
}
Array.from(buttons).forEach((el) => {
el.addEventListener('click', setContainerActive)
});
.main-container {
/* Defaults */
}
.main-container.is-active {
/* Active */
background: red;
}
/* Example */
.main-container .show-is-active { display:none; }
.main-container.is-active .show-is-active { display: block; }
.main-container .hide-is-active { display:block; }
.main-container.is-active .show-hide-active { display: none; }
<div class="main-container">
<h6 class="main-artist"><em class="main-emph">content</em>content</h6>
<p class="main-p"><span class="moreText"> Lorem ipsum </span></p>
<button class="readMore"><span class="show-is-active">read less</span><span class="show-hide-active">read more</span></button>
</div>
HTML:
<div class="main-container">
<h6 class="main-artist">
<em class="main-emph">content</em> content
</h6>
<p class="main-p">
<span class="moreText"> Lorem ipsum dolor, sit amet consectetur adipisicing elit. Tempora aliquid at, provident molestiae necessitatibus ullam culpa debitis, dolorum quas accusamus quidem iusto eaque omnis veniam. Delectus quo saepe enim voluptatum! </span>
</p>
<button class="readmore">Read more</button>
</div>
<div class="main-container">
<h6 class="main-artist">
<em class="main-emph">content</em>content
</h6>
<p class="main-p">
<span class="moreText"> Lorem ipsum dolor, sit amet consectetur adipisicing elit. Tempora aliquid at, provident molestiae necessitatibus ullam culpa debitis! </span>
</p>
<button class="readmore">Read more</button>
</div>
<div class="main-container">
<h6 class="main-artist">
<em class="main-emph">content</em>content
</h6>
<p class="main-p">
<span class="moreText"> Lorem ipsum dolor, sit amet consectetur adipisicing elit. Tempora aliquid at, provident molestiae necessitatibus ullam culpa debitis, dolorum quas accusamus quidem iusto eaque omnis veniam. Delectus quo saepe enim voluptatum! </span>
</p>
<button class="readmore">Read more</button>
</div>
JS File locations:
If your js file is in the <head></head> you must have it wait for the document to load or the document.querySelectAll(); will not work if the js file is executed before the document is fully loaded. You will get a console error. Defer the js file in the head
<head>
<script src="your-js-file-name.js" defer></script>
</head>
or place js file at the end of the document before the </body> close tag.
<body>
<scrpit src="your-js-file-name.js"></script>
</body>
JS:
let btn = document.querySelectorAll('.readmore');
let mainText = document.querySelectorAll('.main-p');
let container = document.querySelectorAll('.main-container');
// console.log(btn);
// console.log(mainText);
// console.log(container);
btn.forEach((i) => {
i.addEventListener('click', (evt) => {
// console.log(evt.target.previousElementSibling);
let moreContent = evt.target.previousElementSibling;
let button = evt.target;
// console.log(button);
// console.log(moreContent);
if (moreContent.style.visibility != 'visible') {
console.log("Style not present. Running code block below");
moreContent.style.visibility = 'visible';
evt.target.innerHTML = 'Read less';
} else {
console.log('Style present. Removing and replacing with default style with code block below');
moreContent.style.visibility = 'hidden';
evt.target.innerHTML = 'Read mess';
}
})
});
CSS:
The visibility: hidden; will still allow the element to take up the space it occupies in the document. If this is not ideal then switch the css and js to use display: none; and display: block;. Other ways to approach it as well if a smooth transition is needed on the .main-p element.
.main-container {
border-bottom: 1.5px solid blue;
padding-bottom: 10px;
}
.main-p {
color: white;
background-color: #333;
padding: 15px;
visibility: hidden;
}
let btn = document.querySelectorAll('.readmore');
let mainText = document.querySelectorAll('.main-p');
let container = document.querySelectorAll('.main-container');
// console.log(btn);
// console.log(mainText);
// console.log(container);
btn.forEach((i) => {
i.addEventListener('click', (evt) => {
// console.log(evt.target.previousElementSibling);
let moreContent = evt.target.previousElementSibling;
let button = evt.target;
// console.log(button);
// console.log(moreContent);
if (moreContent.style.visibility != 'visible') {
console.log("Style not present. Running code block below");
moreContent.style.visibility = 'visible';
evt.target.innerHTML = 'Read less';
} else {
console.log('Style present. Removing and replacing with default style with code block below');
moreContent.style.visibility = 'hidden';
evt.target.innerHTML = 'Read more';
}
})
});
.main-container {
border-bottom: 1.5px solid blue;
padding-bottom: 10px;
}
.main-p {
color: white;
background-color: #333;
padding: 15px;
visibility: hidden;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<script src="app.js" defer></script>
<title>Document</title>
</head>
<body>
<div class="main-container">
<h6 class="main-artist">
<em class="main-emph">content</em> content
</h6>
<p class="main-p">
<span class="moreText"> Lorem ipsum dolor, sit amet consectetur adipisicing elit. Tempora aliquid at, provident molestiae necessitatibus ullam culpa debitis, dolorum quas accusamus quidem iusto eaque omnis veniam. Delectus quo saepe enim voluptatum! </span>
</p>
<button class="readmore">read more</button>
</div>
<div class="main-container">
<h6 class="main-artist">
<em class="main-emph">content</em>content
</h6>
<p class="main-p">
<span class="moreText"> Lorem ipsum dolor, sit amet consectetur adipisicing elit. Tempora aliquid at, provident molestiae necessitatibus ullam culpa debitis! </span>
</p>
<button class="readmore">read more</button>
</div>
<div class="main-container">
<h6 class="main-artist">
<em class="main-emph">content</em>content
</h6>
<p class="main-p">
<span class="moreText"> Lorem ipsum dolor, sit amet consectetur adipisicing elit. Tempora aliquid at, provident molestiae necessitatibus ullam culpa debitis, dolorum quas accusamus quidem iusto eaque omnis veniam. Delectus quo saepe enim voluptatum! </span>
</p>
<button class="readmore">read more</button>
</div>
</body>
</html>
Hope this helps you out and anyone else having a similar problem to solve. :)

CPU overheating when uploading images with JavaScript

The problem is simply that I wrote the code below to upload random text and images with the same name but the last number in names changed, but this leads to an increase in the processor temperature,
here is the code :
let ctn=document.getElementById("y_main");
function mainCtn(str,i){
var post= ` <section class="y_post">
<article class="y_post_article">
<h3>${str}</h">
<p> Lorem ipsum dolor sit amet consectetur adipisicing elit.
Enim error dolores nulla vero animi a ex perspiciatis repellendus neque
doloremque! Dolor culpa odio ea, excepturi eaque in similique tempore earum!</p>
<img width="200px" src="image/postimage/img_post${i}.pn" alt="post img">
</article>
<section class="y_post_btn">
<button class="post_lbtn"><img src="icon/check.svg" alt="chat" srcset=""></button>
<button class="post_cobtn"><img src="icon/chat-square-text.svg" alt="chat" srcset=""></button>
<button class="post_shbtn"><img src="icon/share.svg" alt="chat" srcset=""></button>
</section>
<div class="y_comment_block">
<button class="close_btn_comment">close</button>
<p class="text_comment"></p>
<div class="comment_tool">
<textarea name="" class="input_comment" cols="30" rows="1" placeholder="insert comment"></textarea>
<button class="btn_comment">add</button>
</div>
</div>
</section>`
return post;
}
let b=1;
setInterval(function () { if(b<12){
ctn.innerHTML+=mainCtn(`#${b}`,b);b++;
}
else{
clearInterval(myInterval);
}
}, 2000);
Just like #KompjoeFriek mentioned you need the setInterval ID, not an id you hardcode.
let b =1
const myInterval = setInterval(function () {
if(b<12){
ctn.innerHTML+=mainCtn(`#${b}`,b);b++;
} else{
clearInterval(myInterval);
}
}, 2000);
This should work.

changing background images in JavaScript not working

i want in seconds the background image in landing page changes automatically
but it dosn't change and i don't know why and i wrote correctly the code
and here is my path images
img/img1.jpg,
img/img2.jpg,
and so on
<div class="landing-page">
<div class="overlay"></div>
<div class="header-area">
<div class="logo">
special design
</div>
<ul class="links">
<li>About </li>
<li>Service </li>
<li>Products </li>
<li>contact </li>
</ul>
</div>
<div class="introduction-text">
<h1>We Are <span class="main-color">Creative Agency</span></h1>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Atque et quidem nostrum tempore ab delectus totam in ducimus! Quae amet corrupti magni et. Adipisci officia at ipsum iste accusantium ullam!</p>
</div>
</div>
my javascript code page
var myBackground = document.getElementsByClassName('landing-page');
var myImages =[
'img1.jpg',
'img2.jpg',
'img3.jpg',
'img4.jpg',
];
myRandomNumber = Math.floor(Math.random() * myImages.length);
console.log(myRandomNumber);
setInterval(() => {
var randomNumber = myRandomNumber;
myBackground.style.backgroundImage = 'url("img/' + myImages[myRandomNumber] + '")';
}, 1000);
changeImage(myBackground,myImages);
"use strict";
window.addEventListener('load', onLoaded, false);
var myImages = ['img1.jpg', 'img2.jpg', 'img3.jpg', 'img4.jpg'];
function onLoaded(event) {
setInterval(
() => {
let tgtElem = document.querySelector('.loading-page');
let randIndex = Math.floor(Math.random() * myImages.length);
tgtElem.textContent = `img/${myImages[randIndex]}`;
tgtElem.style.backgroundImage = `url("img/${myImages[randIndex]}")`;
}, 1000
);
}
header {
background-color: #888;
color: #ddd;
}
<header>
<h1>title</h1>
</header>
<div class='loading-page'>
</div>

Get data of p element of div element jquery

I want to know how can i get data of p element which is a children of div element. remember there are many div elements with same classes. it would be better to use events. As i am beginner I am unable to do it.
jQuery(document).ready(function($) {
$(".wp-block-wish-block-01-wish-block-01-editable").find('.social-link').on('click', function(event) {
var elementText = $(event.target).text();
console.log(elementText);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wp-block-wish-block-01-wish-block-01-editable share-block-content">
<p class="ab-testimonial-title">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Atque porro incidunt error nostrum, labore saepe pariatur similique officia voluptatem! Repellendus iure commodi aliquid nemo nisi rerum quasi sunt, ducimus libero!. </p>
<div class="block-share-links">
<strong>Share:</strong>
<div class="share-links">
<a class="social-link" href="#"><img src="http://localhost/cs/wp-content/plugins/wish-block/assets/021-facebook.png"></a>
<img src="http://localhost/cs/wp-content/plugins/wish-block/assets/043-twitter.png">
<img src="http://localhost/cs/wp-content/plugins/wish-block/assets/049-stumbleupon.png">
</div>
</div>
</div>
There are many blocks like this. What i want to do is that when user clicks the .social-link the text of first element p should be logged in console using jQuery or JavaScript.
This should solve your problem. It searches for the closest parent of the clicked element which has the specified class. Then it looks for the first child element (because of the >) with the specified class and extracts its text.
$('.social-link').click(function() {
var value = $(this).closest('.share-block-content').find('> .ab-testimonial-title').text();
console.log(value);
});
I suppose all of these blocks share the class share-block-content. Then it would be possible to get the text of the <p> element like this:
$(".social-link").on("click", function() {
let text = $(this).closest(".share-block-content").find("p").text();
console.log(text);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wp-block-wish-block-01-wish-block-01-editable share-block-content">
<p class="ab-testimonial-title">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Atque porro incidunt error nostrum, labore saepe pariatur similique officia voluptatem! Repellendus iure commodi aliquid nemo nisi rerum quasi sunt, ducimus libero!. </p>
<div class="block-share-links">
<strong>Share:</strong>
<div class="share-links">
<a class="social-link" href="#"><img src="http://localhost/cs/wp-content/plugins/wish-block/assets/021-facebook.png"></a>
<img src="http://localhost/cs/wp-content/plugins/wish-block/assets/043-twitter.png">
<img src="http://localhost/cs/wp-content/plugins/wish-block/assets/049-stumbleupon.png">
</div>
</div>
</div>
What i want to do is that when user clicks the .social-link the text of first element p should be logged in console
You can do this easily by using the .closest() method to find the closest parent element with class as share-block-content and then find the first p inside that div like:
jQuery(document).ready(function($) {
$(".wp-block-wish-block-01-wish-block-01-editable").find('.social-link').on('click', function(event) {
var elementText = $(this).closest('.share-block-content').find('p:first').text();
console.log(elementText);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wp-block-wish-block-01-wish-block-01-editable share-block-content">
<p class="ab-testimonial-title">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Atque porro incidunt error nostrum, labore saepe pariatur similique officia voluptatem! Repellendus iure commodi aliquid nemo nisi rerum quasi sunt, ducimus libero!. </p>
<div class="block-share-links">
<strong>Share:</strong>
<div class="share-links">
<a class="social-link" href="#"><img src="http://localhost/cs/wp-content/plugins/wish-block/assets/021-facebook.png"></a>
<img src="http://localhost/cs/wp-content/plugins/wish-block/assets/043-twitter.png">
<img src="http://localhost/cs/wp-content/plugins/wish-block/assets/049-stumbleupon.png">
</div>
</div>
</div>

Delete an element from the code using jquery

I'm trying Jquery and now I have a problem.
I want to remove an element from my webpage. So, when I press the delete button - the big element must disappear. Using the JQ I have written something like this
$(document).ready(function(){
$(".delete").click(function(){
$(this).parents(".block").animate({ opacity: 'hide' }, "slow");
})
});
It have worked fine until I didn't add subdiv, or answer. And how the application must works now? I press the delete button and it must remove current block.
<div class = "block">
<div class = "postbuttons">
<img src = "img/delete-icon.png" class = "delete"></a>
<img src = "img/edit-icon.png" class = "edit"></a>
</div>
<div class = "postinfo">
<span class = "author">Da Monkey wrote:</span> <span class = "date">on <span>13.13.13</span></span>
</div>
<div class = "post">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ea, voluptate, unde, impedit iste sint assumenda consequatur ipsum nesciunt</p>
<a class = "answerlink" href = "#">Answer</a>
</div>
<div class = "answer">
<div class = "postbuttons">
<img src = "img/delete-icon.png" class = "delete"></a>
<img src = "img/edit-icon.png" class = "edit"></a>
</div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fuga, numquam, culpa, omnis explicabo ut asperiores ipsam porro alias quisquam nisi iste non a maiores! Nulla odio unde dolorum officia vero. </p>
<div class = "answerinfo">
- Macaque on <span>13.13.13</span>
</div>
</div>
If you didn't understand me here the result
Respect to the funcionality:
$(document).ready(function(){
$(".delete").click(function(){
$(this).closest(".block").animate({ opacity: 'hide' }, "slow");
});
});
you should use closest instead of parents because it stop once it has found the first math and parents travels to the root of the dom. Also if you dont need the block anymore you can remove it with the jquery method remove(), after tue animation ended with a callback function.
Also you are missing some semicolons, and tags
$(document).ready(function(){
$(".delete").click(function(){
$(this).parents(".block").animate({ opacity: 'hide' }, "slow");
}) // here needs a semicolon
});
Missing tags
<div class = "block">
<div class = "postbuttons">
<img src = "img/delete-icon.png" class = "delete"></a> <--! missing <a> -->
<img src = "img/edit-icon.png" class = "edit"></a> <--! missing <a> -->
</div>
<div class = "postinfo">
<span class = "author">Da Monkey wrote:</span> <span class = "date">on <span>13.13.13</span></span>
</div>
<div class = "post">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ea, voluptate, unde, impedit iste sint assumenda consequatur ipsum nesciunt</p>
<a class = "answerlink" href = "#">Answer</a>
</div>
<div class = "answer">
<div class = "postbuttons">
<img src = "img/delete-icon.png" class = "delete"></a> <--! missing <a> -->
<img src = "img/edit-icon.png" class = "edit"></a> <--! missing <a> -->
</div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fuga, numquam, culpa, omnis explicabo ut asperiores ipsam porro alias quisquam nisi iste non a maiores! Nulla odio unde dolorum officia vero. </p>
<div class = "answerinfo">
- Macaque on <span>13.13.13</span>
</div>
</div>
I hope I was Useful.
Try hiding the container of the container of the delete button, which will work regardless of its class:
$(document).ready(function(){
$(".delete").click(function(){
$(this).parents(".postbuttons").parent().animate({ opacity: 'hide' }, "slow");
})
});

Categories

Resources