Show and hide divs on click - javascript

What am I doing wrong? I am trying to show divs when the thumbnail is clicked. I am able to show the first div, but for some reason, the next div is not showing. I cannot figure out what I might be missing.
<script>
$(function(){
$('.clickImage').click(function(){
$('.popUp').hide();
$('.popUp').eq($(this).index()).show();
});
});
</script>
<style>
.popUp{
display:none;
}
</style>
<div id="projectContainer">
<div class="imageV clickImage"></div>
<div class="textVertical">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean vel tortor sit amet magna condimentum dapibus non quis nulla. Etiam varius pellentesque quam sed faucibus. Ut libero mi, porta ac tincidunt sagittis, porttitor a elit. In non tellus eu mauris tristique gravida. In rutrum arcu ullamcorper risus consequat interdum. Sed rutrum rhoncus dolor. Suspendisse potenti.</div>
<div class="imageV clickImage"></div>
<div class="textVertical">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean vel tortor sit amet magna condimentum dapibus non quis nulla. Etiam varius pellentesque quam sed faucibus. Ut libero mi, porta ac tincidunt sagittis, porttitor a elit. In non tellus eu mauris tristique gravida. In rutrum arcu ullamcorper risus consequat interdum. Sed rutrum rhoncus dolor. Suspendisse potenti.</div>
</div>
<div>
<div class="popUp">Enlarged Image 1</div>
<div class="popUp">Enlarged Image 2</div>
</div>

Try including a selector in the .index() method:
$(function(){
$('.clickImage').click(function(){
$('.popUp').hide();
$('.popUp').eq($(this).index(".clickImage")).show();
});
});

Your first clickable clickImage will work because it will return index:0.
Which is the right corresponding popup.
But for the second clickImage it will return index:2, which does not have a corresponding popup. Only 0 and 1 are present.
This is because .textVertical is also seen as a sibling of clickImage, thus the 2nd clickImage you clikc will be the 3rd sibling (index).
Change
$('.popUp').eq($(this).index()).show();
To
$('.popUp').eq($(this).index('.clickImage')).show();
http://jsfiddle.net/rNSLE/

I don't think index() is doing what you are intending for it to do.
I would use a dataImageId attribute or something similar to uniquely identify the images.

Try this way:
<script>
$(function(){
$('.clickImage').click(function(){
$('.popUp').hide();
$(this).next().next().show();
});
});
</script>
<style>
.popUp{
display:none;
}
</style>
<div id="projectContainer">
<div class="imageV clickImage"></div>
<div class="textVertical">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean vel tortor sit amet magna condimentum dapibus non quis nulla. Etiam varius pellentesque quam sed faucibus. Ut libero mi, porta ac tincidunt sagittis, porttitor a elit. In non tellus eu mauris tristique gravida. In rutrum arcu ullamcorper risus consequat interdum. Sed rutrum rhoncus dolor. Suspendisse potenti.</div>
<div class="popUp">Enlarged Image 1</div>
<div class="imageV clickImage"></div>
<div class="textVertical">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean vel tortor sit amet magna condimentum dapibus non quis nulla. Etiam varius pellentesque quam sed faucibus. Ut libero mi, porta ac tincidunt sagittis, porttitor a elit. In non tellus eu mauris tristique gravida. In rutrum arcu ullamcorper risus consequat interdum. Sed rutrum rhoncus dolor. Suspendisse potenti.</div>
<div class="popUp">Enlarged Image 2</div>
</div>

your index is 2 as selected, use something like this:
$('.clickImage').click(function () {
var i=$('.clickImage').index(this);
$('.popUp').hide();
$('.popUp').eq(i).show();
});
index is 0 based.
Note that the first returns 0 as it is the first div, and 2 on the second as it is the third div, so you need to isolate to the divs with the .clickImage class
Here is a simple fiddle to demonstrate: http://jsfiddle.net/zfZE2/

Related

changing the html DOM via javascript not responding

I am changing the background of a div with a function. The following is my html code:
$scope.Background = 'img/seg5en.png';
document.getElementById("Bstyle").style.background = "url("+$scope.Background+") no-repeat center fixed;";
console.log(document.getElementById("Bstyle").style.background);
console.log("url("+$scope.Background+") no-repeat center fixed;");
Originally, $scope.Background is equal to "img/bg.png" which is specified on top of my document.
The first console.log prints that the value of style.background as "img/bg.png".
However, the second console.log prints: url(img/seg5en.png) no-repeat center fixed.
I do not understand why my html page does not update though.
Please change DOM using angularised way
Use ng-style to change style of element from JavaScript.
In angular you can assign value to $scope variable and it can be access to your view.
Here is demo for resolve your issue
function ChangeBackground($scope) {
$scope.Background = 'https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcQdNIsxlrqB0Bqy-qmamo6tt9fdqqL9p43Bf5oy11xt0UuAa9vAILYjMX7_';
$scope.changeImage = function(){
$scope.Background ='https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcQ2I2AW0JI-scAY0Phe321d1Yi8UHbFhsIk8OXTbpfEfaNf9F4V9lt60rs';
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="ChangeBackground">
<div ng-style="{'background': 'url(' + Background + ')'}" > Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla porttitor mi non consequat varius. Curabitur libero tellus, placerat in metus nec, porttitor facilisis mi. Vivamus nec mattis felis. Cras mattis in mi sed feugiat. Sed ut hendrerit nisi, at tincidunt nibh. Donec vel malesuada orci. Nunc auctor tortor in mi consectetur gravida. Phasellus eleifend erat lectus, convallis tincidunt nisi euismod et. Donec a ornare eros, et eleifend magna. Phasellus viverra pellentesque metus, in lacinia tortor egestas nec. Suspendisse luctus dolor sit amet nisi interdum, nec commodo orci consectetur. Phasellus pretium vulputate viverra. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</div>
<input type="button" value="Change Background" ng-click="changeImage()"/>
</div>

capture overflow text height using javascript

i am using overflow:hidden property in the css which makes the text to be hidden when it goes outside the container.
can any one please let me know if there is a way to capture the height of the whole text including the overflow text
as well. height() value is just returning me the height of the container and not the overflow text ?
Use scrollHeight, see documentation.
$('#id')[0].scrollHeight
Live demo
JQuery
$('document').ready(function(){
$("#info").text("Width of real text: "+$('.real').css('width'));
$("#info").html($("#info").html() + "<br/>Height of real text: "+$('.real').css('height'));
});
HTML
<div class="overflow">
<div class="real">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse non justo eget eros accumsan mattis. In a auctor magna, sit amet dapibus sapien. Mauris lectus justo, ornare eu pretium in, fringilla nec risus. Phasellus at risus dapibus, imperdiet tellus lacinia, feugiat risus. Nullam ultrices luctus ante, id aliquet eros. In iaculis elit ut hendrerit facilisis. Cras tristique non orci non sodales. Aliquam semper libero sed diam venenatis, imperdiet rhoncus augue eleifend. Nullam euismod mauris neque, ac semper erat posuere a. Nam a tortor commodo, adipiscing nisl vel, sollicitudin nisl. Suspendisse adipiscing laoreet neque sit amet tempor.
</div>
</div>
<div id="info"></div>
CSS
.overflow{
width:200px;
height:100px;
overflow:hidden;
}
.real{
width:300px;
}
#info{
background-color:gray;
margin-top:15px;
}

Set height of certain div on click through jquery function in a-tag

I'd like to expand a certain story-div when a button inside the div is clicked.
i.e: An overview of reviews shows only the first few sentences of a review. When a button is clicked the review expands to full height.
<div id="overview">
<div class="story">
<div class="naam">John Doe</div>
<div class="plaats">Washington DC, USA</div>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam at accumsan augue. Curabitur ac tortor felis. Quisque fringilla est at neque congue commodo. Proin metus libero, condimentum sed viverra et, pulvinar eget nisi. Donec viverra arcu ut ante adipiscing laoreet. In non tellus leo. Suspendisse ultrices eros quis odio fermentum id commodo ligula tempus. Nunc tincidunt suscipit dolor, nec tempus quam mattis non. Sed dapibus odio nec nisl ultricies vel commodo dolor sagittis.
</p>
<a class="readMore" href="javascript:openStory();" title="Read more">Read more ›</a>
</div>
<div class="story">
<div class="naam">John Doe</div>
<div class="plaats">Washington DC, USA</div>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam at accumsan augue. Curabitur ac tortor felis. Quisque fringilla est at neque congue commodo. Proin metus libero, condimentum sed viverra et, pulvinar eget nisi. Donec viverra arcu ut ante adipiscing laoreet. In non tellus leo. Suspendisse ultrices eros quis odio fermentum id commodo ligula tempus. Nunc tincidunt suscipit dolor, nec tempus quam mattis non. Sed dapibus odio nec nisl ultricies vel commodo dolor sagittis.
</p>
<a class="readMore" href="javascript:openStory();" title="Read more">Read more ›</a>
</div>
</div>
.story has a fixed height of 120px. I'd like to set its height to 'auto' with the openStory(); function.
function openStory(){
this.parent('.story').css('height','auto');
}
Help is appreciated
$('.readMore').click(function(event) { // Bind click event to all .readMore elements
event.preventDefault(); // Prevent the default click action
$(this) // Refers to the clicked .readMore element
.parent() // Get parent element. Assuming it´s the .story element?
.css('height', 'auto'); // set CSS rule. But why not use a CSS class?
});
..and replace href="javascript:openStory();" with href="#".
Used this in the end to open/close the div:
$('.review .story a.readMore').click(function(){
animatingElement = $(this).parent('.story');
if(animatingElement.hasClass('open')){
animatingElement.removeClass('open');
} else {
animatingElement.addClass('open');
}
});
Until Stefan came up with the toggleClass-function
$('.review .story a.readMore').click(function(){
animatingElement = $(this).parent('.story');
animatingElement.toggleClass('open');
});
That's the way to go.

Toggle an Image on Click

I'm trying to toggle an image on Click. It's partially working but also partially not :'(
Demo: http://jsfiddle.net/Tqwdh/4/.
When I click the large image, the smaller image changes (from 50x50 to 151x151) - hurrah!
But when I click the 'Read more' text, the small image remains the same image. The small, nested image needs to change when I click the 'Read more' text.
Can anyone show me how I can resolve this?
I've attached my jQuery:
$(function(){
// The height of the content block when it's not expanded
var adjustheight = 130;
// The "more" link text
var moreText = "Click to read more...";
// The "less" link text
var lessText = "Click to read less...";
// Sets the .more-block div to the specified height and hides any content that overflows
$(".more-less .more-block").css('height', adjustheight).css('overflow', 'hidden');
// The section added to the bottom of the "more-less" div
$(".more-less").append('<p style="display:block;margin-top:8px"></p>');
$("a.adjust").text(moreText);
$(".adjust").toggle(function() {
$(this).parents("div:first").find(".more-block").css('height', 'auto').css('overflow', 'visible');
// Hide the [...] when expanded
$(this).parents("div:first").find("p.continued").css('display', 'none');
$(this).text(lessText);
}, function() {
$(this).parents("div:first").find(".more-block").css('height', adjustheight).css('overflow', 'hidden');
$(this).parents("div:first").find("p.continued").css('display', 'block');
$(this).text(moreText);
});
});
$(function(){
$('img').click(function(){
$(this).closest('article').find('.adjust').click();
});
});
$(function(){
$("article").click(function(){
$("img.small").attr('src',
($("img.small").attr('src') == 'http://placehold.it/50x50'
? 'http://placehold.it/151x151'
: 'http://placehold.it/50x50'
)
)
});
});
and my HTML:
<article id="post-5" >
<div class="more-less">
<div class="more-block">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed diam purus, lacinia eget placerat sit amet, bibendum nec nisl. Curabitur a mattis ipsum. Praesent quis nisi in purus malesuada rhoncus. Pellentesque ut quam eget libero congue lobortis. Nunc sed quam ac erat lobortis eleifend. Donec elementum sodales cursus. Aliquam porttitor massa nisi, in laoreet turpis. Sed consequat condimentum lorem ut dignissim. Sed hendrerit mauris ut massa fermentum laoreet. Pellentesque a leo vitae enim dictum lobortis. Praesent commodo feugiat velit iaculis malesuada.</p>
<p>Praesent sem lectus, ullamcorper eget ullamcorper a, congue vel nisl. Nullam volutpat leo vel dui venenatis dapibus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus ac scelerisque lorem. Ut blandit magna eu turpis posuere gravida. Fusce egestas risus in libero ullamcorper sagittis. Vestibulum molestie metus vitae quam dignissim consequat. Vivamus id tellus id lorem consectetur iaculis sit amet interdum ante. Quisque lacinia tellus id mi tincidunt fermentum dignissim velit laoreet. Quisque scelerisque nunc iaculis nisi varius ultrices.</p>
<p>Phasellus id elit ac lacus faucibus ullamcorper. Etiam ullamcorper pretium tellus, ut pharetra ante pulvinar vel. Sed neque diam, semper vel rhoncus non, congue ut sapien. Integer a mi eget libero elementum lobortis. Donec hendrerit egestas ligula sit amet eleifend. Curabitur pharetra venenatis tempor. Quisque pulvinar malesuada justo, ut euismod arcu pharetra vitae. Cras lobortis, ligula id euismod euismod, ipsum risus varius urna, faucibus gravida lectus mi nec nulla. Fusce eleifend fringilla nibh ut vulputate. Vivamus sagittis leo metus. Etiam facilisis convallis lacus adipiscing hendrerit. Duis ultricies euismod libero, nec blandit est semper a. Phasellus sit amet justo sed quam elementum lobortis. Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</div>
</div>
<p>
<img src="http://placehold.it/50x50" class="small" style="position:absolute;margin-left: 240px;margin-top: 127px;" />
<img src="http://placehold.it/300x187" alt="News Item 1" width="300" height="187" />
</p>
</article>
Many thanks for any pointers.
So, if I have understood you correctly, all you've got to do is,
Change this
$("article").click(function() {
//your code here
});
to,
$("article, .adjust").click(function() {
//your code here
});
Check the fiddle here
EDIT:
Changed a couple of things to match what you needed,
1) Change this,
$(this).parents('article').find('.adjust').click();
to,
$(this).parents('article').find('.adjust').trigger('click');
as the latter is a proper way to trigger an event.
2) Change in the image swap function,
$("article, .adjust").click(function() {
/*Save references in variables*/
var imgToSwap = $(this).parents("article").find("img.small");
var img_small = 'http://placehold.it/50x50';
var img_large = 'http://placehold.it/151x151';
imgToSwap.attr('src', (imgToSwap.attr('src') == img_small ? img_large : img_small));
});
Using $(this) will help you get the image in the right context.
Check the fiddle test here
It looks like you have a few problems here. I don't see that you've applied the adjust class to any element in your HTML. I also see that CSS is applied directly in JavaScript. (Why not use a .css file?)
This part of the code looks very nice:
$("img.small").attr('src',
($("img.small").attr('src') == 'http://placehold.it/50x50'
? 'http://placehold.it/151x151'
: 'http://placehold.it/50x50' ))
This is good use of the ternary operator.
My I suggest that you use this code as the click handler on a.adjust, assuming that the link that expands the image is supposed to be decorated with the adjust class?
var changeImage = function() {
$("img.small").attr('src',
($("img.small").attr('src') == 'http://placehold.it/50x50'
? 'http://placehold.it/151x151'
: 'http://placehold.it/50x50' ))
});
$('a.adjust').click(changeImage);
$('article').click(changeImage);
I hope this helps. If the question were written more precisely, it might be helpful.

jQuery Expand/Collapse with header

I have tried using the accordion plugin, but it does not work, and I know there is a simpler solution using pure jQuery.
In essence, I would like it so that when you click a <h2> with the class="expand", it should 'expand' the next div with class="collapse". All the divs should be collapsed by default.
Any help would be much appreciated, thanks in advance!
For testing purposes see this jsFiddle demo.
const $headers = $('.header');
const $contents = $('.content');
$headers.on("click", function() {
const $cont = $(this).next(".content");
$contents.not($cont).slideUp(); // Hide all
$cont.slideToggle(); // Toggle one
});
.header { background: #ddd; cursor: pointer; margin: 0; }
.content{ display:none; }
<h2 class="header">Click to expand and collapse</h2>
<div class="content">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean bibendum dolor nec nunc aliquam placerat. Nullam vehicula nibh felis. Nulla tincidunt aliquam nisl nec sagittis. Donec convallis hendrerit nisl, ut lacinia elit sagittis a. Nullam sollicitudin
ultricies nibh, tincidunt adipiscing erat tristique vitae. Sed id ipsum ac ipsum fringilla molestie et sit amet elit. Cras commodo augue id dolor suscipit commodo. Ut varius porta orci, quis dignissim ante adipiscing et. Pellentesque rhoncus purus ut
tortor tempus auctor.</div>
<h2 class="header">Click to expand and collapse 2</h2>
<div class="content">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean bibendum dolor nec nunc aliquam placerat. Nullam vehicula nibh felis. Nulla tincidunt aliquam nisl nec sagittis. Donec convallis hendrerit nisl, ut lacinia elit sagittis a. Nullam sollicitudin
ultricies nibh, tincidunt adipiscing erat tristique vitae. Sed id ipsum ac ipsum fringilla molestie et sit amet elit. Cras commodo augue id dolor suscipit commodo. Ut varius porta orci, quis dignissim ante adipiscing et. Pellentesque rhoncus purus ut
tortor tempus auctor.</div>
<h2 class="header">Click to expand and collapse 3</h2>
<div class="content">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean bibendum dolor nec nunc aliquam placerat. Nullam vehicula nibh felis. Nulla tincidunt aliquam nisl nec sagittis. Donec convallis hendrerit nisl, ut lacinia elit sagittis a. Nullam sollicitudin
ultricies nibh, tincidunt adipiscing erat tristique vitae. Sed id ipsum ac ipsum fringilla molestie et sit amet elit. Cras commodo augue id dolor suscipit commodo. Ut varius porta orci, quis dignissim ante adipiscing et. Pellentesque rhoncus purus ut
tortor tempus auctor.</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
It hides all opened elements before collapsing the closed one.
And it toggles the open state if the element is opened.
This is simple, just use the below
$('.expand').click(function() {
$(this).next('.collapse').slideToggle(); // or use .toggle() for no animation
});
Fiddle: http://jsfiddle.net/garreh/WQYc7/2/
To be collapsed by default just add the below css:
.collapse {
display: none;
}
Use jQuery, I've updated your Fiddle.
HTML:
<div id="accordion">
<h2 class="toggle">Click to expand and collapse</h2>
<div class="pane">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean bibendum dolor nec nunc aliquam placerat. Nullam vehicula nibh felis. Nulla tincidunt aliquam nisl nec sagittis. Donec convallis hendrerit nisl, ut lacinia elit sagittis a. Nullam sollicitudin ultricies nibh, tincidunt adipiscing erat tristique vitae. Sed id ipsum ac ipsum fringilla molestie et sit amet elit. Cras commodo augue id dolor suscipit commodo. Ut varius porta orci, quis dignissim ante adipiscing et. Pellentesque rhoncus purus ut tortor tempus auctor.
</div>
<h2 class="toggle">Click to expand and collapse 2</h2>
<div class="pane"><br>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean bibendum dolor nec nunc aliquam placerat. Nullam vehicula nibh felis. Nulla tincidunt aliquam nisl nec sagittis. Donec convallis hendrerit nisl, ut lacinia elit sagittis a. Nullam sollicitudin ultricies nibh, tincidunt adipiscing erat tristique vitae. Sed id ipsum ac ipsum fringilla molestie et sit amet elit. Cras commodo augue id dolor suscipit commodo. Ut varius porta orci, quis dignissim ante adipiscing et. Pellentesque rhoncus purus ut tortor tempus auctor.
</div>
</div>
​
Javascript:
<script>
$(document).ready(function() {
$('#accordion h2').click(function() {
var $nextDiv = $(this).next();
var $visibleSiblings = $nextDiv.siblings('div:visible');
$(this).toggleClass('current').siblings('h2').removeClass('current');
if ($visibleSiblings.length ) {
$visibleSiblings.slideUp('fast', function() {
$nextDiv.slideToggle('fast');
});
} else {
$nextDiv.slideToggle('fast');
}
});
});​
</script>
CSS:
.toggle {
background: gray;
padding: 5px;
cursor: pointer;
}
.pane { display: none; }
​.current { background: green }

Categories