How to toggle a specific div class inside loop - javascript

I'm finding no exact word to make you understand. I better show you my code:
<?php while($row=mysqli_fetch_array($res)){ ?>
<button class="btn<?php echo $row['id']; ?>">Button</button>
<p hidden class="area<?php echo $row['id']; ?>">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Magni beatae vero perspiciatis atque praesentium animi, non? Voluptatem, tempora fugiat quos animi facilis facere obcaecati enim reiciendis excepturi sunt! Ducimus, modi!
</p>
<?php } ?>
<script>
$('.btn').click(function(){ // Can't set the specific number beside .btn
$('.area').show(); // Can't set the specific number beside .area
});
</script>
I want to make my work done for specific class. No idea how I can get the exact classname from and tag.
I expect:
<script>
$('.btn1').click(function(){
$('.area1').show();
});
$('.btn2').click(function(){
$('.area2').show();
});
$('.btn3').click(function(){
$('.area3').show();
});
--------------- and so on -------------
</script>
Hope you understand this.

If you have the exact HTML, assign a common class i.e. btn and area and then use DOM relationship to target the desired element.
<button class="btn">Button</button>
<p class="area">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Magni beatae vero perspiciatis atque praesentium animi, non? Voluptatem, tempora fugiat quos animi facilis facere obcaecati enim reiciendis excepturi sunt! Ducimus, modi!
</p>
Script
$('.btn').click(function(){
$(this).next('.area').toggle();
});
However if you don't have the exact HTML, you can still use a common class to bind event handler using custom data-* attribute.
<button class="btn" data-target=".area<?php echo $row['id']; ?>">Button</button>
<p class="area<?php echo $row['id']; ?>">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Magni beatae vero perspiciatis atque praesentium animi, non? Voluptatem, tempora fugiat quos animi facilis facere obcaecati enim reiciendis excepturi sunt! Ducimus, modi!
</p>
then use
$('.btn').click(function(){
$($(this).data('target')).toggle();
});

Related

createElement in another html page?

I am trying to create an App which has 2 html files, index.html and bookmarks.html. Index.html has some question cards which contain some text and a bookmarks button.
My goal is that when I press the bookmark button in the question card from index.html, that card should be replicated in bookmarks.html.
I was thinking to use the createElement approach, but I have no idea how to do this when the elements that should be created are on a different page...
For more clarity, here is the html code for the question cards in index.html:
<section class="question-card">
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsam vitae
labore repudiandae tenetur. Qui maiores animi quibusdam voluptatum
nobis. Nam aperiam voluptatum dolorem quia minima assumenda velit
libero saepe repellat. Tempore delectus deleniti libero aliquid rem
velit illum expedita nostrum quam optio maiores officiis consequatur
ea, sint enim cum repudiandae inventore ab nemo? Eum dicta illum odio
harum, commodi similique. Lorem ipsum, dolor sit amet consectetur
adipisicing elit. Inventore maxime ipsa accusamus, soluta provident
tenetur aliquid ad nisi voluptate iste quaerat ab ullam voluptatem
illo eos optio ut dolor nostrum.
</p>
<button type="button" class="qc-bookmark-icon">
<img src="/assets/bookmark-icon.jpeg" alt="bookmark icon"/>
</button>
</section>
And this is what it looks like, with the bookmark button on the top-right corner.
Do you have any idea if this would be the right approach and if yes, how could I implement this?
If not, I am open to any suggestions, how I could make this work...
Thank you.

Click in an html tag and display another that is initially hidden

Each <p> are hidden on initial load and I want to click on the <h3> then want the p-tag to show using Javascript.
I have a section in my HTML that looks as follow
<div id="bio-sections">
<div id="history">
<h3 onclick="openFunction()">My History</h3>
<p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Fuga alias hic officia dolor quidem maiores quasi architecto veritatis obcaecati debitis, rem suscipit quo blanditiis perspiciatis deleniti id a rerum quae!</p>
</div>
<div id="schooling">
<h3>My Schooling</h3>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. In iure distinctio voluptatum non quia maxime numquam amet eum at, quo ut iusto est quos hic placeat. Repudiandae dolorem cupiditate illo.</p>
</div>
<div id="work">
<h3>My Work experience</h3>
<p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Quisquam dolor nemo nostrum consequuntur. Tempora, quia nobis eligendi, labore porro natus voluptates nam, consectetur corporis vitae eius hic sed ea earum.</p>
</div>
<div id="hobbies">
<h3>My Hobbies</h3>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Dolor perspiciatis ipsam suscipit voluptas ab distinctio a doloribus, dolorem officia iure nemo qui incidunt soluta dolores ratione saepe. In, mollitia! Voluptatem!</p>
</div>
</div>
My question is how do you reference the following div (or in this case p-tag) given the H3 you pressed?
If you press the H3 under #history then only that p-tag must show and the same with the other divs. But how do you do this in Javascript without duplicating code with different id's or classes.
My approach avoid the use of inline JS inside HTML, which is a bad practice.
Select all <h3> that are clickable and should open the <p> tags, then add the listener to them all.
Now, all you need is the function using this, that refers to the clicked h3, get it's sibling element, check if it is displaying or not, and do the toggle.
See below code
openFunction = function(ev) {
let pTagElem = this.nextElementSibling
if (pTagElem.style.display == "inline") {
pTagElem.style.display = "none"
} else {
pTagElem.style.display = "inline"
}
}
//select all <h3> that should be clickable (inside bio-sections divs)
let h3s = document.querySelectorAll("#bio-sections div h3")
//add the listener to them all
for (let h3 of h3s) {
h3.onclick = openFunction
}
#bio-sections div p {
display: none
}
#bio-sections div h3 {
cursor: pointer
}
<div id="bio-sections">
<div id="history">
<h3>My History</h3>
<p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Fuga alias hic officia dolor quidem maiores quasi architecto veritatis obcaecati debitis, rem suscipit quo blanditiis perspiciatis deleniti id a rerum quae!</p>
</div>
<div id="schooling">
<h3>My Schooling</h3>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. In iure distinctio voluptatum non quia maxime numquam amet eum at, quo ut iusto est quos hic placeat. Repudiandae dolorem cupiditate illo.</p>
</div>
<div id="work">
<h3>My Work experience</h3>
<p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Quisquam dolor nemo nostrum consequuntur. Tempora, quia nobis eligendi, labore porro natus voluptates nam, consectetur corporis vitae eius hic sed ea earum.</p>
</div>
<div id="hobbies">
<h3>My Hobbies</h3>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Dolor perspiciatis ipsam suscipit voluptas ab distinctio a doloribus, dolorem officia iure nemo qui incidunt soluta dolores ratione saepe. In, mollitia! Voluptatem!</p>
</div>
</div>
you can use javascript parameters like this, and move the id into the p tag
<div>
<h3 onclick="openFunction('history')">My History</h3>
<p id="history">Lorem, ipsum dolor sit amet consectetur adipisicing elit. Fuga alias hic officia dolor quidem maiores quasi architecto veritatis obcaecati debitis, rem suscipit quo blanditiis perspiciatis deleniti id a rerum quae!</p>
</div>
<script>
function openFunction(id) {
document.getElementById(id).show()
}
</script>
You can use closest() and delegation.
const container = document.querySelector("#bio-sections");
container.addEventListener("click", function (event) {
const parentSectionDiv = event.target.closest(".section");
if (parentSectionDiv !== null) {
parentSectionDiv.querySelector("p").classList.remove("hidden");
}
});
.hidden {
display:none;
}
<!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="style.css" /> -->
<title>Sign in & Sign up Form</title>
</head>
<body>
<div id="bio-sections">
<div id="history" class="section">
<h3>My History</h3>
<p class="hidden">
Lorem, ipsum dolor sit amet consectetur adipisicing elit. Fuga alias
hic officia dolor quidem maiores quasi architecto veritatis obcaecati
debitis, rem suscipit quo blanditiis perspiciatis deleniti id a rerum
quae!
</p>
</div>
<div id="schooling" class="section">
<h3>My Schooling</h3>
<p class="hidden">
Lorem ipsum dolor sit amet consectetur adipisicing elit. In iure
distinctio voluptatum non quia maxime numquam amet eum at, quo ut
iusto est quos hic placeat. Repudiandae dolorem cupiditate illo.
</p>
</div>
<div id="work" class="section">
<h3>My Work experience</h3>
<p class="hidden">
Lorem ipsum dolor, sit amet consectetur adipisicing elit. Quisquam
dolor nemo nostrum consequuntur. Tempora, quia nobis eligendi, labore
porro natus voluptates nam, consectetur corporis vitae eius hic sed ea
earum.
</p>
</div>
<div id="hobbies" class="section">
<h3>My Hobbies</h3>
<p class="hidden">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Dolor
perspiciatis ipsam suscipit voluptas ab distinctio a doloribus,
dolorem officia iure nemo qui incidunt soluta dolores ratione saepe.
In, mollitia! Voluptatem!
</p>
</div>
</div>
</body>
<script src="script.js"></script>
</html>
It depends a bit on how stable your HTML is, but if you are confident it remains like that you don't need to change it and can on the click get the p element.
There's several ways of doing this. This snippet gets the common parent and the first p element in it.
function openFunction() {
console.log(event.target);
console.log(event.target.parentElement.querySelector('p:first-of-type'));
}
<div id="bio-sections">
<div id="history">
<h3 onclick="openFunction()">My History</h3>
<p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Fuga alias hic officia dolor quidem maiores quasi architecto veritatis obcaecati debitis, rem suscipit quo blanditiis perspiciatis deleniti id a rerum quae!</p>
</div>
<div id="schooling">
<h3>My Schooling</h3>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. In iure distinctio voluptatum non quia maxime numquam amet eum at, quo ut iusto est quos hic placeat. Repudiandae dolorem cupiditate illo.</p>
</div>
<div id="work">
<h3>My Work experience</h3>
<p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Quisquam dolor nemo nostrum consequuntur. Tempora, quia nobis eligendi, labore porro natus voluptates nam, consectetur corporis vitae eius hic sed ea earum.</p>
</div>
<div id="hobbies">
<h3>My Hobbies</h3>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Dolor perspiciatis ipsam suscipit voluptas ab distinctio a doloribus, dolorem officia iure nemo qui incidunt soluta dolores ratione saepe. In, mollitia! Voluptatem!</p>
</div>
</div>

Iterating with Each Quiz Jquery

$('p').each(function (index) {
var letters = $(this).text().length;
$('p').appendTo('<span> Here is ' + letters + '</span>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Lorem</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. A amet vel fugit repellendus, magni blanditiis delectus autem dicta, omnis odit beatae iusto asperiores, iste. Delectus, eaque reiciendis quibusdam cupiditate molestias officia perspiciatis corporis cumque saepe voluptatem, magnam magni asperiores a!</p>
Hello There , I will appreciate a lot any help with my code , I need to count all letters per one <p> Tags and show it on the end of <p> tag but my code count all of <p> tags which I have on the page and put it together in every of them , can any body give me advise what is . wrong and how to fix it , Thank you so much
Because $('p') will find every <p> in page the same way you are using it to set up the initial query
You want the specific instance inside the each which is $(this) and you want append() not appendTo()
$('p').each(function (index) {
var letters = $(this).text().length;
$(this).append('<span style="color:red"> Here is ' + letters + '</span>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Lorem</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. A amet vel fugit repellendus, magni blanditiis delectus autem dicta, omnis odit beatae iusto asperiores, iste. Delectus, eaque reiciendis quibusdam cupiditate molestias officia perspiciatis corporis cumque saepe voluptatem, magnam magni asperiores a!</p>
$('p').each(function (index) {
$('<span></span>',{text : " Here is " + $(this).text().length + ""}).css({color:'blue'}).appendTo(this);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Lorem</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. A amet vel fugit repellendus, magni blanditiis delectus autem dicta, omnis odit beatae iusto asperiores, iste. Delectus, eaque reiciendis quibusdam cupiditate molestias officia perspiciatis corporis cumque saepe voluptatem, magnam magni asperiores a!</p>

Hide and show 1 time clicking Jquery

The effect i got right now, it's shows the div paragraph . But when I add another div it's like all div shows paragraph together . How to control this by clicking 1 at the time?
Your help really appreciate.
HTML
<div class="content">
<button class="open">See More</button>
<p class="ranch">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Maiores iste illum, pariatur ipsa, harum explicabo enim sed temporibus. Autem sint recusandae eligendi, doloremque illum rem possimus odit non deserunt libero!</p>
</div>
<div class="content">
<button class="open">See More</button>
<p class="ranch">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Maiores iste illum, pariatur ipsa, harum explicabo enim sed temporibus. Autem sint recusandae eligendi, doloremque illum rem possimus odit non deserunt libero!</p>
</div>
JS
$('.open').on('click',function(event){
$('.ranch').toggle();
});
DEMO
You are using $('.ranch').toggle(); so you are selecting all paragraphs with class ranch and thus all paragraph are toggled when you click on it. A quick fix will be changing the line to $(this).siblings('.ranch').toggle();
The final JavaScript will be
$('.open').on('click',function(event){
$(this).siblings('.ranch').toggle();
});
JSBin: http://jsbin.com/fiwosigike/1/edit?html,css,js,output
You need to handle the button within each div separately
$('.open').on('click',function(event){
$(this).next('p').toggle();
});
This will do it. You have to use this to toggle only one item.
$('.open').on('click',function(event){
event.preventDefault();
$(this).next('.ranch').toggle();
});
try this.
$( ".open" ).click(function() {
$(this).next(".ranch").slideToggle( "slow", function() {
// Animation complete.
});
});
.content{
width:400px;
background-color:orange
}
.ranch{
display:none;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class="content">
<button class="open">See More</button>
<p class="ranch">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Maiores iste illum, pariatur ipsa, harum explicabo enim sed temporibus. Autem sint recusandae eligendi, doloremque illum rem possimus odit non deserunt libero!</p>
</div>
<div class="content">
<button class="open">See More</button>
<p class="ranch">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Maiores iste illum, pariatur ipsa, harum explicabo enim sed temporibus. Autem sint recusandae eligendi, doloremque illum rem possimus odit non deserunt libero!</p>
</div>
</body>
</html>

Skrollr & Z-index

I've got a bit of an issue with skrollr & z-index.
http://i.imgur.com/whCViHV.png
I'm trying to have the picture at the top to go underneath the blog post.
I can't for the life of me work out why, no matter where/how I apply the z-index (I assume that's what I should be doing) the image ALWAYS sits above the post.
I've tried everything I can think of, putting it inside divs, inside the css...
You can make it go underneath the blog post by putting the post in the skrollr div, but then I run into lots of issues with line height.
I've stripped all my failed z-index attempts out, so it should be 'conflict free' of my old, stupid code.
http://jsfiddle.net/8fb4C/ (not 100% sure that this is correctly done)
https://github.com/pxlprfct/Blog-SO-Question
<div id="skrollr-body">
<div id="test"
data-0="top:0px;"
data-1000="top: 400px;" >
<img src="apple.jpg" alt="">
</div>
</div>
<article>
<h1>
Hi there helpful person!
</h1>
<p>
Hi there, I've been trying, and failing, to do what I thought was a reasonably simple thing.
</p>
<p>
I just want the picture to stay where it is, (don't worry about the horrible aspect ratio and how it looks crushed, I'm fixing that after) and the 'blog', well the article to overlap it.
</p>
<p>
I've been pratting around with z-index and have done pretty much everything I can think of, but the image still persists to scroll on top of the text (rather than underneath).
</P>
<p>
I have tried a few sketchy things that worked, but didn't work well. I think i'm missing something mega obvious, anyways. Thanks for being awesome :)
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Deserunt earum eum recusandae accusantium porro facere vero nulla delectus. Adipisci, omnis velit molestias nemo expedita! Ad, enim similique placeat rerum. Libero.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Maiores, fuga eius ipsa alias repudiandae itaque neque totam veniam ut minus dignissimos eveniet dicta unde quos enim possimus optio nihil omnis. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Placeat, magni est officia quis vitae veritatis doloribus laudantium corporis doloremque ratione ut ullam voluptatibus numquam quos optio voluptas veniam corrupti repellat. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ad, provident, maxime beatae ea distinctio aperiam dicta ipsa soluta consequatur eius explicabo cumque possimus iure temporibus laudantium eveniet et ex placeat.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Incidunt, quidem sint labore saepe explicabo aspernatur sunt vero quos minima nesciunt velit et debitis est accusantium eveniet dolorum sed quibusdam voluptate!
</p>
</article>
Adding position: fixed and tweaking the z-index to -1 does the trick. You also have to set the top and left to 0, but that's secondary:
#test {
position: fixed;
top: 0;
left: 0;
z-index: -1;
}
JSFiddle:
http://jsfiddle.net/8fb4C/1/

Categories