Find height of class and apply to another class - javascript

I've been looking around the web for an answer for a couple of hours and cannot find anything so I'm hoping someone can help me.
I want to take the height of a wrapper div who's class is movie and apply it to an inner div who's class is movie-center. How can I do this using JS or jQuery?
I am a newbie when it comes to JS, so I would really appreciate if you could lay everything out for me (including any HTML needed).
Thank you!
EDIT 1: Maybe if I am explaining what I am doing people will have a better understanding. I am making a responsive WordPress theme. As the width of the browser is smaller, the movie widths are smaller. I want the overlay title and graphic to stay in the center. I tried doing this with CSS and it cannot be done fully unless I know the exact height (which I won't because of resizing).
EDIT 2: here is the browser's rendered html code:
<article id="movie-97" class="post-97 movie type-movie status-publish hentry"><a href="http://localhost:8888/movies/hard-truth-levity-hope">
<div class="movie-center">
<div class="movie-overlay">
<div class="movie-play"></div>
<h2 class="movie-title">Hard Truth, Levity and Hope</h2>
</div> <!-- end .movie-overlay -->
</div> <!-- end .movie-center -->
<div class="movie-thumb"><img width="480" height="270" src="http://localhost:8888/wp-content/uploads/2014/03/truth-levity-hope.jpg" class="attachment-movie-thumb wp-post-image" alt="Hard Truth, Levity and Hope" /></div>
EDIT 3: Here's a Pastebin for my website. Note: it has been stripped down to only show the essential parts of the site.

What you've done is the correct way. Make sure you've loaded jQuery properly and try to wrap your code inside DOM ready handler $(document).ready(function() {...}); or shorter form $(function() {...});
$(function() {
$('.movie').each(function() {
var h = $(this).height();
$(this).find('.movie-center').height(h);
});
});
Edit: Since you're using Wordpress, there's probably a conflict happen here, try to use:
jQuery(document).ready(function($) {
$('window').resize(function() {
$('.movie').each(function() {
var h = $(this).height();
$(this).find('.movie-center').height(h);
});
}).resize();
});

Please try this :
/* Get height of .movie thumb preview */
jQuery(document).ready(function($) {
$('.movie').each(function() {
var h = $(this).height();
console.log(h);
$(this).find('.movie-center').first().css('height',h);
console.log($(this).find('.movie-center').first().height())
});
});

Connor,
This will get you what you're looking for:
jQuery(document).ready(function($) {
$('.movie').each(function() {
var h = $(this).height();
$(this).find('.movie-center').height(h);
});
});
A quick explanation. You'll notice that jQuery's .height() function is called twice. First, without any params and then with h passed in.
Pull up your JS console (cmd+opt+j if you're using Chrome) to see how this actually works.
The question at the top of this page has an id of #question-header, so if you enter this in the console $('#question-header').height() you'll see that it returns 36. That's because that element is 36 pixels tall.
So, calling .height without any params will return the height of the selected element. But, we can set the height by passing in a number. Try this by pasting this in to the JS console:
$('#question-header').height(1000)
The header is now 1000px tall!
The third line of the code basically says, "Hey, within this particular instance of the .movie article, find the .movie-center element and set the height.
So, there you go. Some working code and hopefully an explanation as to exactly why/how to use it in the future.

Related

How to set full page background Image of a div that changes on page load

I tried but couldn't get it done.
I want the background of a div to cover full page according to the device width and it should change each time when page is load or refresh on same system.
I have tried many codes but none of them works for me.
Now the script that i am using is:
<script type="text/javascript">
window.onload=function(){
var thediv=document.getElementById("image");
var imgarray = new Array("../bgimages/1.png", "../bgimages/2.png", "../bgimages/3.png");
var spot =Math.floor(Math.random()* imgarry.length);
thediv.style.background="url("+imgarray[spot]+")";
}
</script>
The HTML code is as follows
<html>
<body>
<div id="image">
<div class = "container">
</div> <!--container ends-->
</div>
I want #image div background to cover full page.
This is the CSS i am using:
#image
{
width:100%;
height:100%;
background-repeat:no-repeat;
background-size:cover;
background-position:center;
}
Here is the link of the page: http://sahibfreelancer.hostzi.com/
No background image loading.
Please if i miss anything you can let me know. I hope i gave enough details. I am trying this from last one day.
Will be looking forward to your responses.
I spotted a typo :
var spot =Math.floor(Math.random()* imgarry.length);
... should be ...
var spot =Math.floor(Math.random()* imgarray.length);
... shouldn't it ? Does it work if you edit that ?
Since you have jQuery in the tags, I'm going to assume you're using jQuery.
But that being said you're not using the $ syntax in your code examples.
Here's how you can set the background with jQuery:
$('#image').css('background-image', 'url(' + imageUrl + ')');
Edit:
Looks like Ashugeo got it. Next time check the console for the output of your script, it would have been throwing an exception.
Also, if you are using jQuery, there's nicer ways to do what you're doing.
To make the image occupy the entire screen you can specify the viewport height in css like this #image {height:100vh}
Now for the javascript code everything looks fine to me if the images are in the specified url it should load them randomly. You can see a example here.
the only thing i've done is load the images over the web since i cant access them locally on fiddle. A different Image is loading every time.
As for the page load i've used a immediately invoking function which will fire when the contents are loaded but you can use onload as well.
I think its the path of your images.
I pasteD your code and change the url and it works http://jsbin.com/pozadujeca/edit?js,console,output

How to get zoom working with turn.js

I am trying to make a flipbook using turn.js that has the same functionality as the example on the website http://www.turnjs.com/samples/magazine/
When looking at how to achieve this I came across these pages
http://www.turnjs.com/docs/Method:_zoom
http://turnjs.com/docs/How_to_add_zoom_to_turn.js
But after following these instructions on the pages my flipbook works nothing like the sample one.
I tried using the sample provided and breaking it down into sections to get mine working but I have not gotten any closer to solving this problem and the sample contains a bunch of other scripts and I am not sure if they are required for the zoom or are used for other things.
Not sure if I am missing something really simple or if my code is really off but my html looks something like this.
Right now all I get when clicking the zoom button is that the book scales up 150%
Was wondering if anyone could tell me what I am missing to get that zoom?
<div class="row">
<div id="zoom-viewport">
<div id="flipbook">
// wordpress loop
<div class="page">
// page contents
</div>
// end loop
</div>
</div>
</div>
and jQuery
//----------------------------
// Initialize
var _width = $('#flipbook-wrap').width(),
_height = Math.round(70.909090909/100*_width),
_winWidth = $window.width(),
_winHeight = $window.height();
$("#flipbook").turn({
width: _width,
height: _height,
autoCenter: true
});
//----------------------------
// Zoom in button
$('.fullscreen').click(function(e){
e.preventDefault();
$("#flipbook").turn("zoom", 1.5);
});
Your code isn't showing everything (e.g. where ".fullscreen" or the "zoom button" is in your HTML), so my answer may not be precise.
Looking at the sample, you should find the code:
$('.magazine-viewport').zoom('zoomIn', pos);
This seems to differ from turn('zoom', ...), and appears to be undocumented. This is a function that will zoom in the element defined as a turn object. I believe, for you, this is your "#flipbook" element, instead of ".magazine-viewport".
The parameters are "zoomIn" and pos, which may be a different functionality that what you're using currently. The "pos" appears to be a JS object that contains "x" and "y" properties, meant to define where you clicked on the magazine. These coordinates are relative to the magazine, not the whole screen, so keep that in mind.
So, I think you need something like this (at least try it at a starting point):
$('#flipbook').click(function(e) {
var pos = {
x: e.pageX - $(this).offset().left,
y: e.pageY - $(this).offset().top
};
$('#flipbook').zoom('zoomIn', pos);
});
Hope this helps!
To get zoom to work with turn.js, there are three things you need to do:
Setup the proper dom structure, zoom won't work without the "container" div to wrap the flipbook.
<div class="magazine-viewport">
<div class="container">
<div class='magazine'>
<div id='p1'><img src='book_1.jpg'></div>
<div id='p2'><img src='book_2.jpg'></div>
</div>
</div>
</div>
Setup the js events
$( document ).ready(function() {
//Initialize the turn.js flipbook
$('.magazine').turn({
width: 1136,
height:734,
pages:100,
autoCenter: false,
when:{
missing: function (e, pages) {
for (var i = 0; i < pages.length; i++) {
$('.magazine').turn('addPage',page[pages[i]],pages[i]);
}
}
}
});
//Initialize the zoom viewport
$('.magazine-viewport').zoom({
flipbook: $('.magazine')
});
//Binds the single tap event to the zoom function
$('.magazine-viewport').bind('zoom.tap', zoomTo);
//Optional, calls the resize function when the window changes, useful when viewing on tablet or mobile phones
$(window).resize(function() {
resizeViewport();
}).bind('orientationchange', function() {
resizeViewport();
});
//Must be called initially to setup the size
resizeViewport();
}
function page(num){
var elem = $('<div />',{}).html('<div><img src="book_'+num+'.jpg></div>');
return elem;
}
function zoomTo(event) {
setTimeout(function() {
if ($('.magazine-viewport').data().regionClicked) {
$('.magazine-viewport').data().regionClicked = false;
} else {
if ($('.magazine-viewport').zoom('value')==1) {
$('.magazine-viewport').zoom('zoomIn', event);
} else {
$('.magazine-viewport').zoom('zoomOut');
}
}
}, 1);
}
function resizeViewport() {
var width = $(window).width(),
height = $(window).height(),
options = $('.magazine').turn('options');
$('.magazine-viewport').css({
width: width,
height: height
}).zoom('resize');
}
Define proper css styles for the elements, the trick here is that the negative coordinates of the magazine class is compensated by the top & left offsets of the container class.
.magazine-viewport .container{
position:absolute;
top:367px;
left:568px;
width:1136px;
height:734px;
margin:auto;
}
.magazine-viewport .magazine{
width:1136px;
height:734px;
left:-568px;
top:-367px;
}
/* Important: the image size must be set to 100%.
* Otherwise the position of the images would be messed up upon zooming.
*/
.magazine img{
width:100%;
height:100%;
}
That should get it to work, if you want to load a larger version of the image upon zooming, take a look at the loadSmallPage() & loadLargePage() functions in the magazine example.
I had the same problem, but I decided to just use a third party zoom plugin (Jack Moore's jQuery zoom). It turns out the example in the site is a lot more complicated, with a json to create diferent regions and images for each paragraph.
It really depends on what you're using turn.js for, but I think the documentation isn't right, or the software itself is missing something. Either way, I do suggest you look into using some other solution for the problem.
turn.js provides an example with zoom. The difficulty to make it work is to gather all the required files. But if you watch the code, it is possible. Say the root is magazine, it goes two folders up to get lib and extras folders where java scripts are laying. In addition, you have to add the "default" and large pages in the pages folder. When you get the sample, there are only the thumbnails in. Say for 1-thumb.jpg, you have to add 1.jpg and 1-large.jpg
There is a very usefull Firefox plugin to get them : CacheViewer.
I have managed to do it with my book, and reorganize the paths in the code to have something cleaner: put lib and extras at the same level than pages. A recursive grep for "/../../" will give you all the locations in html and js code.

Resize EpicEditor based on the content put within it

I'm using epiceditor within my site, and I am populating it with markdown embedded on the page by the server. Currently when epiceditor displays, it has a very small default height, with scroll bars to handle viewing the entire content. I can manually set the height of the div, and for now that's the best I've been able to do (I've set it to something reasonably large: 800px). However I would like its height to always be enough to fit the entire content without scroll-bars. Essentially something like overflow:visible.
Here's the relevant portions so far
<html>
<head>
<script src="/assets/javascripts/epiceditor/js/epiceditor.min.js" type="text/javascript"></script>
<script id="postMarkdown" type="text/markdown" data-postId="1">
#Markdowns in here
...
</script>
<style>
#epiceditor{
height: 800px;
}
</style>
<script src="/assets/javascripts/thrown/posts/edit.js" type="text/javascript"></script>
</head>
<body>
<div id="epiceditor">
</div>
</body>
</html>
And heres the edit.js source (its compiled from coffescript)
$ ->
postMarkdown = $("#postMarkdown").first()
options =
basePath : '../../assets/javascripts/epiceditor'
editor = new EpicEditor(options).load()
postId = postMarkdown.data('postId')
markdown = postMarkdown.html()
editor.importFile('posts/'+postId,markdown);
editor.reflow();
I was hoping reflow might expand the height after the content was inserted, however no such luck. However If I resize the div and call reflow, It does resize properly.
I've inspected the markup it creates in hopes I could determine the height and resize its container and tell it to reflow. However it seems it contains multiple iframes, and at a glance I didn't expect that to be a quick change, or if it would even be possible. However I'd welcome any solution.
I also understand that if I size its container to the right height, epiceditor will fill the proper space. However I want its height to be the amount needed to render, such that the editor takes up the right space in the rest of the sites design. Therefore if there something I can set in EpicEditor to have it not overflow in the manner it is, or a way to determine the height after it loads, I'm set.
Thanks for any help.
I'm the guy who made EpicEditor, here's a solution for you:
var editor = new EpicEditor({
basePath: 'https://raw.github.com/OscarGodson/EpicEditor/develop/epiceditor'
});
var updateEditorHeight = function () {
editorHeight = $(editor.getElement('editor').body).height();
// +20 for padding
$('#epiceditor').height(editorHeight + 20);
editor.reflow();
}
editor.load(function (){
updateEditorHeight();
});
editor.on('update', function () {
// You should probably put a check here so it doesn't
// run for every update, but just on update, AND if the
// element's height is different then before.
updateEditorHeight();
});
Also, in the CSS I added a overflow: hidden to epiceditor's wrapper so the scrollbars don't appear as it grows.
DEMO: http://jsbin.com/eyidey/1/
DEMO CODE: http://jsbin.com/eyidey/1/edit
UPDATE
As of EpicEditor 0.2.2 autogrow is built in. Just turn on the autogrow option.

Stopping jQuery equal height divs from calculating hidden content

I am using the following jQuery to giv certain divs with the id's #main, #sidebar, #side-event equal height. On most pages, I am using .hide(); to toggle information within the content section of the site. The problem is when JS caluclates the height of the #main div, it's calculating all of the hidden content as well, which I do not want. How can I alter my code so that the height is equal to the tallest div, and not include the hidden information in the equation? In addition I added the code I am using to hide the information upon page load. Here is my page from the site for referencing the issue. Hoping someone can help me with this issue.
http://shadowfaxdigital.com/cdi/events/mba-essentials-business-design-workshops/
Calculating height:
$("#main, #sidebar, #side-event").addClass("heights");
var highestCol = Math.max($('#main').height(),$('#sidebar').height(), $("#side-event").height());
$('.heights').height(highestCol);
Code used to hide the content in the toggles:
//jQuery toggle
$(".toggle_container").hide();
$("h2.trigger").click(function(){
$(this).toggleClass("active").next().slideToggle("slow");
});
you can add the visible selector, this will check if the element has display:none or opacity:0
var $sfd = jQuery.noConflict();
var cols = $sfd('#main:visible, #sidebar:visible, #side-event:visible');
var maxHeight = 0;
$(cols).each(function(){
$(this).addClass('heights');
maxHeight = Math.max($(this).height(), maxHeight);
});
$sfd('.heights').height(maxHeight);
It's not entirely clear what exactly you're asking for help with. .height() will only include the height of child elements that take up space in the layout. So an item that was hidden with .hide() will be marked display:none and will not be included in the height of any parent elements. But an item that has a zero opacity or visibility:hidden will take up space in the layout and will be included in a parent's height.
In jQuery, you can see if anything is visible with:
$("#main").is(":visible");
Or, you can put it directly into a selector to only include visible items:
$("#main:visible")
So, you could change your code to something like this if you only want to include the visible items in your selector:
var visibleItems = $("#main:visible, #sidebar:visible, #side-event:visible");
var highestCol = Math.max.apply(this, visibleItems.map(function() {
return $(this).height();
}).get());
I ran into this issue aswell today. Googled alot and found this thread. Seems this wasn't properly solved, therefore I'm posting my solution:
My issue was that the height-adjusting script was calculating the heights before the elements were successfully hid with jQuery, I therefore copied my height-equalizing script into a $(document).ready(function() {} );
Like this:
$(document).ready(function()
{
if ($('.sidebar').height() < $('#mainwindow').height())
{
var mainwindowHeight = $('#mainwindow').height();
$(".sidebar").css('height', mainwindowHeight+8+'px');
}
});
This solved it for me.
Hope this helps someone.

div max-height set dynamically using javascript

I have a web app using master page and content pages (see the attached image). I need to set max-width of one div in content page dynamically accordint to the browser window size (so that the whole app stays on the page, without scrolling). I couldn't find the sloution (or couldn't replicate the results) using just html and CSS. So I'm thinking to do it using javascript. But the problem is, I NEVER used it, so I really have no clue how to do it. I'd really appriciate if someone took a couple of minutes and write the function that will do it. As I see it, I should take difference in height between bottom edge of the header and top edge of the footer and subtract height values of searchbar and button bar.
EDIT:
Thanks to maxedison for providing that code. But, how do I use it? :D I'm a total noob. I have a problem, since I use masterpage and content pages. Where do I put that code?
EDIT 2 - THE ANSWER:
I looked a little further into how to use jQuery, and searched here some more, and I found a solution. Next time I start developing an application, I'll use jQuery from the bottoms up...It just simplifies some things so much. :)
So for the solution: It's similar to what maxedison suggested, but I changed it so, that I set height with CSS and I just added a fixed value to deduct from window.height.
<script type='text/javascript'>
$(function () {
$('.myStyle').css({ 'height': (($(window).height()) - 350) + 'px' });
$(window).resize(function () {
$('.myStyle').css({ 'height': (($(window).height()) - 350) + 'px' });
});
});
</script>
Using jQuery, it would look something like:
function resetHeight(){
var newHeight = $(window).height() - $('.header').outerHeight() - $('.searchBar').outerHeight() - $('.buttons').outerHeight() - $('.footer').outerHeight();
$('.content').height(newHeight);
}
$(function(){
newHeight();
$(window).resize(function(){
resetHeight();
});
});

Categories

Resources