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>
Related
Let's say we have this text inside a single <p> that uses the entire screen space:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed vestibulum
sem consectetur, tempor massa quis, bibendum mauris. Curabitur et leo
pharetra, condimentum mi vel, gravida mi. Integer pulvinar nibh in
laoreet auctor. Donec in tortor in augue maximus fermentum et non erat.
Sed auctor feugiat dolor eget efficitur. Vivamus nec urna lorem. Duis
lobortis semper tempor. Vestibulum dolor lectus, consectetur.
If we were using a smaller display, it would look like something this:
Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Sed vestibulum sem
consectetur, tempor massa quis, bibendum
mauris. Curabitur et leo pharetra,
condimentum mi vel, gravida mi. Integer
pulvinar nibh in laoreet auctor. Donec
in tortor in augue maximus fermentum et
non erat. Sed auctor feugiat dolor eget
efficitur. Vivamus nec urna lorem. Duis
lobortis semper tempor. Vestibulum dolor
lectus, consectetur.
The paragraph has now more lines than before. With that said, I want to convert this single paragraph into one <p> per line to apply different styling to each one of them, but also taking into acount that the number of lines can change from the viewport/browser window size. This is so that the text styling can be responsive.
HTML:
<p>Lorem ipsum dolor sit amet, consectetur</p>
<p>adipiscing elit. Sed vestibulum sem</p>
<p>consectetur, tempor massa quis, bibendum</p>
<p>mauris. Curabitur et leo pharetra,</p>
<p>condimentum mi vel, gravida mi. Integer</p>
<p>pulvinar nibh in laoreet auctor. Donec</p>
<p>in tortor in augue maximus fermentum et</p>
<p>non erat. Sed auctor feugiat dolor eget</p>
<p>efficitur. Vivamus nec urna lorem. Duis</p>
<p>lobortis semper tempor. Vestibulum dolor</p>
<p>lectus, consectetur.</p>
I'm looking for a pure JavaScript (aka no jQuery) solution.
document.body.addEventListener("load", function(){
var defaultCharacterWidth = 8; //8 px
var textboxWidth = document.querySelector(".orgText").offsetWidth;
var breakIndex = Math.floor(textboxWidth/defaultCharacterWidth);
var i = 0;
var savedIndex = 0;
var whitespace = 0;
document.querySelector(".orgText").textContent.match(/[\s\S]/g).forEach(function(element, index){
if (element.match(/\s/))
{
whitespace = index;
}
if (i == breakIndex)
{
i = -1;
//get nearest whitespace
document.querySelector(".textcontainer").innerHTML += "<p>" + document.querySelector(".orgText").value.slice(savedIndex, whitespace) + "</p>";
savedIndex = whitespace; //save the last whitespace
}
i++;
});
}, true);
<textarea class="orgText" style="overflow:hidden;width:100%">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed vestibulum sem consectetur, tempor massa quis, bibendum mauris. Curabitur et leo pharetra, condimentum mi vel, gravida mi. Integer pulvinar nibh in laoreet auctor. Donec in tortor in augue maximus fermentum et non erat. Sed auctor feugiat dolor eget efficitur. Vivamus nec urna lorem. Duis lobortis semper tempor. Vestibulum dolor lectus, consectetur.
</textarea>
<div class="textcontainer">
</div>
This is a little testcode. It uses the fact that a textarea has a fixed character width. But that's not the case for most fonts. The above code iterates over every character and checks if it's exceeds the width of the container based upon the detection of a whitespace character.
You can also use the code below to calculate the width of a string.
function getPixelLengthOfString()
{
var tempNode = document.createElement("span");
tempNode.innerHTML = this;
document.body.appendChild(tempNode);
var stringPixelLength = tempNode.offsetWidth;
document.body.removeChild(tempNode);
return stringPixelLength;
}
These pieces of code should point you in a direction of the correct answer.
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;
}
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.
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/
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 }