Javascript only show elements when class XY is active - javascript

This is my first post here.
i have a big problem. i am in a bootcamp, currently.
I have a site and sections
const bookmarkButton = document.querySelectorAll('.pictureBook')
bookmarkButton.forEach(function (setIt) {
setIt.addEventListener('click', () => {
setIt.classList.toggle('bookmarkChecked')
})
})
.pictureBook {
all: unset;
background-image: url(/img/bookmark-svgrepo-com.svg);
background-size: cover;
width: 100px;
height: 100px;
position: absolute;
top: -15px;
right: -10px;
cursor: pointer;
opacity: 0.5;
}
.bookmarkChecked {
opacity: 1;
}
<section class="main__section">
<h2 class="question__title">Frage</h2>
<p class="question__text">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nulla eius
voluptatibus modi voluptates nisi quam expedita fugiat repudiandae
animi ab.
</p>
<button class="pictureBook"></button>
<button class="showanswer__btn">Antwort anzeigen</button>
<p class="answershowed hideanswer">
Lorem ipsum dolor sit, amet consectetur adipisicing elit. A nemo
libero tempore dolore numquam dolorum sed cumque nihil explicabo
ullam.
</p>
</section>
Now i can click the bookmark "svg" and opacity gone to 100 % ( bookmark set, color black )
I have a button. and i want, only show the "classes" i added the class for bookmarked it.
I am on the Limit. Google doesn`t help. Maybe you can?
When i click another button in my footer, the site Show please only the active sections with the class bookmarkChecked.
Thank you very much.

A bookmarked button has the bookmarkChecked class. So you can use
querySelectorAll to choose only the bookmarked button.
Use forEach to loop over the list of buttons.
Inside the forEach callback get the corresponding section for each button using the closest method
Now you can hide the bookmarked section using a class to set display none.
If all this needs to happen after a button click, then do the following inside an addEventListener.

Related

Span text wrap issue during slideToggle() animation

The problem is that while slideToggle() is animating the span tags don't have proper text wrapping. Only once the animation finishes the span content is wrapper correctly.
I am trying to add more content on button press with jQuery. Not just plop it in, but rather have some kind of animation such as what slideToggle() provides.
Is there a fix for this or how can I implement it slightly differently to avoid the content not wrapping during the animation.
Here is an example:
$('.toggle').click(function() {
$('.moreContent').slideToggle();
});
p {
max-width: 300px;
}
.hide {
display: none;
}
<p>
<span><strong>List: </strong></span>
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Neque, beatae.
<span class="hide moreContent">Lorem, ipsum dolor sit amet consectetur adipisicing elit. Sit voluptate consequuntur corporis sint sequi quam maxime eius iusto perspiciatis.</span>
<br>
<br>
<button class="toggle">Toggle</button>
</p>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
The jump exists because in order to animate the slide the span has to have a height but it can only have a height if it is display: inline-block or display: block, which it means it will also have a width. You can see that jQuery is adding display: inline-block to the style attribute on the element while it's animated. When the animation is done, jQuery removes the style attribute and it goes back to the previous layout, i.e. inline.
I don't know what your use case is or which parts are important (e.g. is the slide animation the important part or simply that something is animated in? Must it end on a sentence? Be two lines? Etc, etc). Below are a couple of examples that might give you some ideas to explore.
First, instead of relying on jQuery to handle the animations, you can use it to toggle a class and define the animation in the CSS. The first example sets the container height to a max of 2em and overflow: hidden (so 2 lines will be shown and the rest hidden). Then, clicking the toggle button toggles the class and when the .show_all class is added, it animates the max-height property which results in a slide animation. The max-height just needs to be big enough to show whatever content might be in the container. If it's hugely variable you could set it to some large number (since it won't take up the space unless it needs it). However, you might need to tweak your animations numbers.
The second example uses opacity and sets the animation to fade the text in/out when toggle is clicked. The hidden text still takes up space, so if you didn't want that, you could play with the CSS to workaround that. Maybe give the hidden text a negative z-index and play with the margin or positioning of the toggle button.
I'm assuming you've set up a simple example so I didn't want to get too much into the details but just wanted to provide some other ways of tackling the problem.
$('.toggle').click(function() {
$('.content').toggleClass('show_all');
});
$('.toggle-fade').click(function() {
$('.showme').toggleClass('show_all');
});
p {
max-width: 300px;
line-height: 1em;
}
.content {
max-height: 2em;
overflow: hidden;
display: inline-block;
transition: max-height .5s ease-in-out;
text-wrap: none;
}
.show_all {
max-height: 10em;
height: auto;
}
.showme {
opacity: 0;
transition: opacity .3s ease-in-out;
}
.showme.show_all {
opacity: 1;
}
<p>
<span><strong>List: </strong></span>
<span class="content">Lorem ipsum dolor sit, amet consectetur adipisicing elit. Neque, beatae.
Lorem, ipsum dolor sit amet consectetur adipisicing elit. Sit voluptate consequuntur corporis sint sequi quam maxime eius iusto perspiciatis.</span>
<br>
<br>
<button class="toggle">Toggle</button>
</p>
<p>
<span><strong>List: </strong></span>
<span class="shown">Lorem ipsum dolor sit, amet consectetur adipisicing elit. Neque, beatae.</span>
<span class="showme">Lorem, ipsum dolor sit amet consectetur adipisicing elit. Sit voluptate consequuntur corporis sint sequi quam maxime eius iusto perspiciatis.</span>
<br>
<br>
<button class="toggle-fade">Toggle</button>
</p>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

Switching Div's on Refresh

I have a div at the top of the page, middle, and bottom. When I refresh the page each time I would like the top and bottom divs to switch without affecting the middle div at all. Thanks in advance for any answers.
My jsfiddle
Code:
.top {
background: lightpink;
padding: 40px;
}
.content {
background: white;
}
.bottom {
background: lightblue;
padding: 40px;
}
<div class="top">
1
</div>
<div class="content">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ullam fuga impedit, obcaecati, commodi dolores quasi odit numquam esse aliquid, alias natus doloribus nihil eius dicta eaque, nobis veritatis! Praesentium, laboriosam.
</div>
<div class="bottom">
2
</div>
It can be done using sessionStorage and cloning divs.
What this is doing is taking a copy of each div in the clone variables and then using a sessionStorage value to toggle between the states. If the sessionStorage value is 0 then it will do nothing but change the value, if it's 1 then it'll remove the divs and then add them in the new order from the cloned content.
var divOne = document.querySelector('.top');
var divTwo = document.querySelector('.bottom');
var divOneClone = document.querySelector('.top').outerHTML;
var divTwoClone = document.querySelector('.bottom').outerHTML;
var divContent = document.querySelector('.content');
if (sessionStorage.getItem('refreshState')) {
if (sessionStorage.getItem('refreshState') == 1) {
divOne.parentNode.removeChild(divOne);
divTwo.parentNode.removeChild(divTwo);
divContent.insertAdjacentHTML('beforebegin', divTwoClone);
divContent.insertAdjacentHTML('afterend', divOneClone);
sessionStorage.setItem('refreshState', 0);
} else {
sessionStorage.setItem('refreshState', 1);
}
} else {
sessionStorage.setItem('refreshState', 0);
}
Here's a working JS Fiddle example.

Prevent Bootstrap collapse item from "jumping"

I've set up a Bootstrap collapse plugin to use with my list of frequently asked questions:
https://jsfiddle.net/2d8ytuq0/
<ul class="faq__questions">
<li>
..
<p class="collapse" id="faq__question_1">...</p>
</li>
</ul>
The problem is when you collapse back the extended description it kind of "jumps". I think this happens due to the bottom margin the p element has. I tried to replace it with padding-bottom, but this didn't solve the issue. Is there any way to fix this without breaking the original layout?
This problem causes because your collapsed element has a margin-bottom:15px.
Your new HTML markup
<div class="collapse" id="faq__question_1">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Saepe nesciunt rerum mollitia nobis corporis sint error quaerat cupiditate animi doloribus! Voluptas dolores, incidunt perspiciatis labore velit libero minus consequuntur blanditiis.</p>
</div>
Simply add this css to override margin property..This works fine
.faq__questions > li p {
margin: 0;
}
You could always add a css transition to it.
I add an active state to the panels and to a css transition on the margin-top.
JS
// Add active class to open panel on faqs accordion
$('.faq__questions').on('show.bs.collapse', 'li', function () {
$(this).addClass('active');
});
$('.faq__questions').on('hide.bs.collapse', 'li', function () {
$(this).removeClass('active');
});
CSS
.faq__questions li .collapse{
margin-top: 0;
transition: all .2s ease-in-out;
}
.faq__questions li.active .collapse{
margin-top: 30px;
}

Loading content into a div [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am trying to create a page with images that upon a user hovering loads content into a div on the same page. So far, I have created the html file and the stylesheet. It's a fairly simple, table-based page, with three images that have the css hover effect on them and link to three different pages. My challenge is figuring out how to load content into the div. I am completely new to Javascript so this is going to be quite the learning curve I imagine but any help will be appreciated. I have attached an image to illustrate what I am trying to do. Thanks everyone]1
Updated question. Thanks for your input everybody. (Back from the holidays - will be going over suggestions)
My css code:
.Image1{
background-image:url('Image1_REG.jpg');
height:86px;
width:86px;
display: block;
}
.Image1:hover {
background-image:url('Image1_Shadow.jpg');
height:86px;
width:86px;
display:block;
}
.Image2{
background-image:url('Image2_REG.jpg');
height:86px;
width:86px;
display: block;
}
.Image2:hover {
background-image:url('Image2_Shadow.jpg');
height:86px;
width:86px;
display:block;
}
.Image3{
background-image:url('Image3_REG.jpg');
height:86px;
width:86px;
display: block;
}
.Image3:hover {
background-image:url('Image3_Shadow.jpg');
height:86px;
width:86px;
display:block;
}
#contentDiv{
height:150px;
width:350px;
left:50px;
top:150px;
position:absolute;
background-color:#452835;}
table {
width:600px;
height:auto;
column-width:200px;
left:150px;
top:150px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="newStyle.css"></link>
</head>
<body>
<body>
<table>
<tbody>
<tr><img src="header.jpg" align ="center" /></tr>
<tr>
<td><a class="Image1" href="http://link1" target="_blank"></a>
</td>
<td>
<a class="Image2" href="http://link2" target="_blank"></a>
</td>
<td><a class="Image3" href="http://link3" target="_blank"></a></td>
</tr>
</tbody>
</table>
<div id="contentDetails">Where the hover text is to be displayed</div>
</body>
</html>
You'll need a small bit of JavaScript but nothing you can't learn in half an hour. I'd advise you read the MDN JS primer but only to get a grasp for how JS works.
In essence you need to locate the element you want to hover over and then have multiple <div>s on your page containing your content. You add a JavaScript mouseover event on the elements you want to hover over and in the callback function you supply to it you tell it to hide all the divs and then display only the div you want.
I think you should be able to work out everything from these pages:
How to get an element in JS
How to add a mouseover event
How to hide and show elements
Best of luck with it. If you're stuck once you've written some code feel free to edit your question and comment on mine (so I know to take a look) and I'll try help.
Here's a very basic example I created that will help get you started:
JS Fiddle:
http://jsfiddle.net/dvav1gdo/5/
HTML
<div class="module">
<div class="tabs">
<div class="tab">
<img style="-webkit-user-select: none;" src="http://dummyimage.com/200x150/000/fff.jpg" width="200" height="150">
</div>
<div class="tab">
<img style="-webkit-user-select: none;" src="http://dummyimage.com/200x150/000/fff.jpg" width="200" height="150">
</div>
<div class="tab">
<img style="-webkit-user-select: none;" src="http://dummyimage.com/200x150/000/fff.jpg" width="200" height="150">
</div>
</div>
<div class="tab-panels">
<div class="tab-panel active">
<div class="content">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Velit unde inventore, aliquam architecto minus minima quis. Aliquid voluptates, dolorum ullam dicta nesciunt molestiae maiores! Ratione quasi officia recusandae laboriosam nihil voluptate perferendis fugiat quae provident aliquam harum id tenetur quisquam, ab repellendus suscipit eligendi temporibus facilis sapiente a veniam voluptatibus quidem in voluptatum vero. Soluta excepturi quisquam, sed, quas rem aperiam atque obcaecati nulla repellendus corporis? Consequatur aut quidem, earum enim asperiores. Libero deserunt dignissimos blanditiis est, repellendus qui molestiae tenetur quas assumenda officiis modi totam, quae ullam. Quaerat officiis tempora molestias voluptatibus sint quo incidunt nostrum quisquam sed excepturi?</p>
</div>
</div>
<div class="tab-panel">
<div class="content">
<p>Lorem ipsum dolor sit amet.</p>
</div>
</div>
<div class="tab-panel">
<div class="content">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Error fugit harum voluptates. Deserunt adipisci libero incidunt nostrum similique laborum dicta, porro natus harum odit, voluptatum vitae, minima iure omnis. Odit, nemo incidunt voluptas placeat est quis ab dolor. Iure, corporis.</p>
</div>
</div>
</div>
</div>
CSS
.tab {
display: inline-block;
}
.tab-panel {
display: none;
&.active {
display: block;
}
}
jQuery
$(document).ready(function () {
var $tabs = $('.tab');
var $panels = $('.tab-panel')
// attach js event handler to all tab jQuery objects
$tabs.on('mouseover', function() {
var $this = $(this);
// get hover index
var hindex = $this.index();
// use the active class to show and hide correct panel based on current hover index
$panels.removeClass('active');
$panels.eq(hindex).addClass('active');
});
});
You could use the hover or click function to detect interaction with the image then you use the div id/name to change the text with query i believe its should be $("").text("Some info")
example:
<div style="height:100px; width:100px" class="title"> //*
first text
</div>
The code that you need in order to change the text in the div which his class name is "title" (SEE comment "//*" above):
$('div.title').text('Some info');
Also See for more information "Use jquery to set value of div tag":
Use jquery to set value of div tag
LINKS:
http://api.jquery.com/text/
http://api.jquery.com/hover/
http://api.jquery.com/click/
Also you can use #tanjir 's code as example:
$('#img1').hover(function(){
$('#contentDiv').text("content for text 1")
};
Remember that
$('#img1'). hover(function(){
// CODE EXECUTE HERE AFTER HOVER OF IMAGE 1
}
*** this example has # in the start because he use the id of the div instead of the class name! so it would look like:
<div ID="img1">
</div>
Is a listener that wait you to hover, when you will hover the code where the comment is will execute.

Dynamically set padding-left based on overlap width of two elements

I've got a responsive site I'm building Where I have two elements that overlap each other. THe size of the elements will change depending on the browser width as will the overlap and consequently I need to set left-padding on the right element dynamically.
I'm unsure of how to proceed with this. Have set up a Fiddle here.
html:
<div class="container">
<div class="row copy intro">
<section class="red">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolor illum nobis ullam neque, harum, magni. Reprehenderit veritatis in deleniti incidunt dolore dolores ex id expedita.</p>
<p>Corporis soluta ducimus ut quasi libero nesciunt, eligendi autem, consequatur error sapiente labore, officia tempora in voluptas non deleniti veniam officiis, quis vero consequuntur quia!</p>
</section>
<section class="white">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolor illum nobis ullam neque, harum, magni. Reprehenderit veritatis in deleniti incidunt dolore dolores ex id expedita.</p>
<p>Corporis soluta ducimus ut quasi libero nesciunt, eligendi autem, consequatur error sapiente labore, officia tempora in voluptas non deleniti veniam officiis, quis vero consequuntur quia!</p>
</section>
</div>
</div><!--container-->
css:
/* line 3, ../build/sass/_intro.scss */
.intro {
background: #0079c2;
position: relative;
padding: 15px;
padding-bottom: 150px;
}
/* line 9, ../build/sass/_intro.scss */
.intro section {
position: relative;
padding: 100px;
width: 60%;
-moz-border-radius: 500px;
-webkit-border-radius: 500px;
border-radius: 500px;
}
/* line 26, ../build/sass/_intro.scss */
.intro section.red {
background: rgba(238, 45, 36, 0.85);
color: #fff;
z-index: 200;
}
/* line 31, ../build/sass/_intro.scss */
.intro section.red h1 {
font-size: 24px;
}
/* line 45, ../build/sass/_intro.scss */
.intro section.white {
background: #fff;
color: #0079c2;
position: absolute;
top: 150px;
right: 15px;
}
js:
// set intro sections width = height
$(document).ready(function() {
var circleWidth= $('.intro section.red').outerWidth();
$('.intro section').css('min-height', circleWidth + 'px');
$('.intro section.white').css('width', circleWidth + 'px');
});
Thank you for your time.
Use % for padding and adjust accordingly. See this revised Fiddle for an example.
The revised Fiddle comments out:
$('.intro section.white').css('width', circleWidth + 'px');
Fixing the width of the white circle means that it is not responsive any more. If you need to do that for some reason, you would have to make adjustments.
Here's a JSFiddle doing what I think you want: http://jsfiddle.net/6yro5vhx/2/
Basically I user offset() & outerWidth() on the two elements to work out the overlap, and then call calculatePadding() function on documentready & resize events.
function calculatePadding() {
var white = $('.intro section.white');
var red = $('.intro section.red');
var extraPadding = 20;
var distanceLeft = white.offset().left;
var redDistanceRight = red.offset().left + red.outerWidth();
var paddingLeft = (redDistanceRight - distanceLeft) + extraPadding;
$('.intro section.white').css('padding-left', paddingLeft + 'px');
}
Update the answer below mine is a far better way to achieve what you're looking for. CSS is a much better responsive approach than excess JQuery.

Categories