CSS/JS Dynamic Width & Font Size - javascript

I have a client site with a navigation feature that has been very tightly designed (and not by me):
It consists of an unordered list, with three DIVs in each list item:
<ul id="application-tabs">
<li>
<div class="cv-home-applications-slideshow-tab-first"></div>
<div class="cv-home-applications-slideshow-tab"><h4>Coffee</h4></div>
<div class="cv-home-applications-slideshow-tab-right"></div>
</li>
<li>
<div class="cv-home-applications-slideshow-tab-left"></div>
<div class="cv-home-applications-slideshow-tab"><h4>Pet Food</h4></div>
<div class="cv-home-applications-slideshow-tab-right"></div>
</li>
</ul>
The content is in the center DIV, while the first/left and right DIVs create the angled tab buttons.
This client has also requested a Google Translate utility up at the top of the page.
My problem is that I need the navigation element to always fill that space from end to end. If the translation produces a shorter word – such as "Cafe" instead of "Coffee" – I need it to expand accordingly.
Likewise, if it results in a longer word, like "Cerveza," I'll need the font size to reduce.
I'm sure I'll need to employ some javascript, in combination with the CSS, but I'm not entirely sure where to start. Any assistance would be appreciated.
Thanks,
ty

here is a fiddle of a solution, it automatically spaces the menu to fit http://jsfiddle.net/nFRjc/
var $j = jQuery.noConflict();
$j(document).ready(function () {
var containerWidth = $j('#application-tabs').width();
var linksWidth = 0;
$j('#application-tabs li div + div').children().each(function () {
linksWidth += $j(this).width();
});
var linkSpacing = Math.floor((containerWidth - linksWidth) / ($j('#application-tabs').children('li').length));
$j('#application-tabs').children().not(':last-child').css('margin-right', linkSpacing + "px");
});​
Ok simple solution to make the font reduce in size if it's too large. See this fiddle, the links font size are 100px, but the script reduces them until they fit. http://jsfiddle.net/nFRjc/2/ I just added a loop that checks whether or not the total width of the individual links is greater than the container width, and reduces the font size by 1 if true.
var $j = jQuery.noConflict();
$j(document).ready(function () {
var containerWidth = $j('#application-tabs').width();
var linksWidth = 0;
$j('#application-tabs li div + div').children().each(function () {
linksWidth += $j(this).width();
});
while (linksWidth >= (containerWidth - 100)) {
$j('#application-tabs li div + div h4').css({'font-size': '-=1'});
var linksWidth = 0;
$j('#application-tabs li div + div').children().each(function () {
linksWidth += $j(this).width();
});
}
var linkSpacing = Math.floor((containerWidth - linksWidth) / ($j('#application-tabs').children('li').length));
$j('#application-tabs').children().not(':last-child').css('margin-right', linkSpacing + "px");
});​

Related

Finding position of element within scrollable div

I have these "pages" aka div's inside a scrollable container. On command, I am trying to find out what part of the div in question, is touching the top of .pageContent.
So for example, right when the page loads, no part of #page_1 is touching the top of pageContent, but as I scroll down. #page_1 hits the top of .pageContent and I now want to figure out where that is.
I know I can get the position of .pageContent using $("#pageContent").scrollTop() but these page's could be different sizes and I am not sure how to go about figuring it out.
Could anyone put me in the right direction?
jsfiddle
HTML
<div id="pageContent">
<div id="page_1" class="content"></div>
<div id="page_2" class="content"></div>
<div id="page_3" class="content"></div>
</div>
CSS
#pageContent {
overflow: auto;
width:500px;
height:300px;
padding:10px;
border:1px solid black;
background-color:grey;
}
.content {
height:400px;
width:300px;
margin:0 auto;
background-color:red;
margin-bottom:10px;
}
You can use the jQuery .position() function to compute where each page is in relation to the top of the container. See this Fiddle.
For example, for #page_1,
var page1 = $('#page_1');
$('#pageContent').scroll(function() {
// page1.position().top gives the position of page_1 relative to the
// top of #pageContent
});
ScrollTop can be used, be I wouldn't recommend it.
Attach a scroll event to your main div and listener for all the objects inside:
$('#pageContent').scroll(function(){
var pages = $("#pageContent > .content");
for (var i = 0; i < pages.length; i++)
{
if ($(pages[i]).position().top < 0 && ( $(pages[i]).position().top + $(pages[i]).outerHeight() ) > 0)
{
var outerHeight = $(pages[i]).outerHeight();
var pixels = (outerHeight - (outerHeight + $(pages[i]).position().top));
console.log("These pixels are in view between: " + pixels + " and " + outerHeight );
}
}
})
Every time the div scroll a loop is performed checking the position of all elements. If the elements scroll out of view a the top the if is triggered, calculating the remaining visible pixels of the page currently visible.
This uses jQuery's: position() and outerHeight() and JavaScript's native offsetTop.
http://jsfiddle.net/q5aaLo9L/4/
I tried something like this
$(document).ready(function () {
var divs = $('.content').map(function (i, el) {
return $(el).offset().top - $(el).parent().offset().top;
});
$('#pageContent').scroll(function () {
var index = findIndex($(this).scrollTop(), divs) - 1;
if (index > -1) {
console.log($(this).children().eq(index).attr('id'));
} else {
console.log('outside');
}
});
});
function findIndex(pos, divs) {
return (divs.filter(function (el, et) {
return et <= pos
}).length);
}
It's not super clean code because I had to do it quickly.
DEMO
I hope this helps
I mocked this up, it uses JQuery's each() function to iterate through the pages and return the information of the page that has breached the top of the box.
I wasn't sure from your question exactly what you wanted returned, so I got it to return either the percentage of the page that has cleared the top border, the position (as negative value of pixels) of the top of the "page " in relation to the content container, and also just the ID of that div.
var getCurrentPage = function(){
var page;
var position;
var percentageRead;
$('.content').each(function(){
if($(this).position().top <= 0){
page = $(this);
position = $(this).position().top;
}
});
percentageRead = ((position *-1)/ $(page).height()* 100);
console.log(page.attr('id'));
console.log(position);
console.log(percentageRead + '%');
}
$('#pageContent').on('scroll', getCurrentPage);
You could fire this on any event but I used scroll to build it.

Menu fixed on single page - change color

i want to create a menu for a single page website with link to div from page.
The menu look like this:
<li>Home</li>
...
<div id="home-link"></div>
I want to change color of link from menu when i am in area of home-link div. How is possible to make that thing?
Thanks for answers and for your help.
Have a nice day.
You will need JavaScript for this if the link element is not a child of #home-link.
Something like this:
$('#home-link').on('hover', function () {
$('li a').css('color', '#bada55');
});
This assumes you are using jQuery, but similar approach with other frameworks would work as well.
If I assume from the question that if you are hovering on #home-link and color of anchor should change, then
$('#home-link').hover(function () {
$('li a').css('color', 'red');
});
or if I assume that if the id is present in your page and you want to change the color of the anchor then
if($('#home-link').length){
$('li a').css('color', 'red');
}
I found myself with (what I believe is) the same question: how can I change which navigation link is highlighted to reflect the area I've scrolled to, whether I get there by using the link or just by scrolling down the page?
Here's a page with a very helpful tutorial.
The theory:
We create an array of all our nav a href’s. We then use some calculations using the scroll function. We find the section id, calculate it’s height, see if it’s greater or less than the value from the window top, and if the window falls in between, we add a class nav-active to the list item in question. We create a conditional also, because if the top of a section is not reached and the page can’t scroll anymore, we want to highlight this section.
And the relevant jQuery code:
/**
* This part handles the highlighting functionality.
* We use the scroll functionality again, some array creation and
* manipulation, class adding and class removing, and conditional testing
*/
var aChildren = $("nav li").children(); // find the a children of the list items
var aArray = []; // create the empty aArray
for (var i=0; i < aChildren.length; i++) {
var aChild = aChildren[i];
var ahref = $(aChild).attr('href');
aArray.push(ahref);
} // this for loop fills the aArray with attribute href values
$(window).scroll(function(){
var windowPos = $(window).scrollTop(); // get the offset of the window from the top of page
var windowHeight = $(window).height(); // get the height of the window
var docHeight = $(document).height();
for (var i=0; i < aArray.length; i++) {
var theID = aArray[i];
var divPos = $(theID).offset().top; // get the offset of the div from the top of page
var divHeight = $(theID).height(); // get the height of the div in question
if (windowPos >= divPos && windowPos < (divPos + divHeight)) {
$("a[href='" + theID + "']").addClass("nav-active");
} else {
$("a[href='" + theID + "']").removeClass("nav-active");
}
}
if(windowPos + windowHeight == docHeight) {
if (!$("nav li:last-child a").hasClass("nav-active")) {
var navActiveCurrent = $(".nav-active").attr("href");
$("a[href='" + navActiveCurrent + "']").removeClass("nav-active");
$("nav li:last-child a").addClass("nav-active");
}
}
});

Getting Coordinates of an element on page scroll

I am having this problem where i have a set of 6 UL's having a common class x.Each of them consist of a specific section of the page.Now i have 6 menus that are related to each of the section.What i have to do is highlight the menu when its related section is in users view.
For this i thought that may be jQuery position(); or offset(); could have helped but they give the top and left of the element.I also tried using jQuery viewport plugin but apparently view port is big it can show more than one UL at a time hence i cant apply element specific logic here.I am not familliar to this but does anything changes of an element on scrolling?If yes then how to access it?
Please share your views.
Regards
Himanshu Sharma.
Is very easy to do it using jQuery and a dummy fixed HTML block that helps you find the current position of the viewport.
$(window).on("scroll load",function(){
var once = true;
$(".title").each(function(ele, index){
if($(this).offset().top > $("#viewport_helper").offset().top && once){
var index = $(this).index(".title");
$(".current").removeClass('current')
$("#menu li").eq(index).addClass('current')
once = false;
}
});
})
Check out a working example: http://jsfiddle.net/6c8Az/1/
You could also do something similar with the jQuery plugin, together with the :first selector:
$(window).on("scroll load",function(){
$(".title:in-viewport:first").each(function(){
var index = $(this).index(".title");
$(".current").removeClass('current')
$("#menu li").eq(index).addClass('current')
});
})
You can get the viewport's width and height via $(document).width() and $(document).height()
You can get how many pixels user scrolls via $(document).scrollTop() and $(document).scrollLeft
Combining 1 and 2, you can calculate where the viewport rectangle is
You can get the rectangle of an element using $(element).offset(), $(element).width() and $(element).height()
So the only thing left to you is to determine whether the viewport's rectangle contains (or interacts) the elements's rectangle
So the whole code may look like:
/**
* Check wether outer contains inner
* You can change this logic to matches what you need
*/
function rectContains(outer, inner) {
return outer.top <= inner.top &&
outer.bottom >= inner.bottom &&
outer.left <= inner.left &&
outer.right >= inner.right;
}
/**
* Use this function to find the menu related to <ul> element
*/
function findRelatedMenu(element) {
return $('#menu-' + element.attr('id'));
}
function whenScroll() {
var doc = $(document);
var elem = $(element);
var viewportRect = {
top: doc.scrollTop(),
left: doc.scrollLeft(),
width: doc.width(),
height: doc.height()
};
viewportRect.bottom = viewportRect.top + viewportRect.height;
viewportRect.right = viewportRect.left + viewportRect.width;
var elements = $('ul.your-class');
for (var i = 0; i < elements.length; i++) {
var elem = $(elements[i]);
var elementRect = {
top: elem.offset().top,
left: elem.offset().left,
width: elem.width(),
height: elem.height()
};
elementRect.bottom = elementRect.top + elementRect.height;
elementRect.right = elementRect.left + elementRect.width;
if (rectContains(viewportRect, elementRect)) {
findRelatedMenu(elem).addClass('highlight');
}
}
}
$(window).on('scroll', whenScroll);
Let's see if i understood well. You have a page long enough to scroll, and there is an element that when it appears in the viewport, you wanna do something with it. So the only event that's is triggered for sure on the time the element gets in the viewport is the 'scroll'. So if the element is on the page and the scroll is on the viewport, what you need to do is bind an action to the scroll event to check if the element is in the view each time the event is trigger. Pretty much like this:
$(window).scroll(function() {
check_element_position();
});
Now, in order for you to know if the element is in the viewport, you need 3 things. The offset top of that element, the size of the viewport and the scroll top of the window. Should pretty much look like this:
function check_element_position() {
var win = $(window);
var window_height = win.height();
var element = $(your_element);
var elem_offset_top = element.offset().top;
var elem_height = element.height();
var win_scroll = win.scrollTop();
var pseudo_offset = (elem_offset_top - win_scroll);
if (pseudo_offset < window_height && pseudo_offset >= 0) {
// element in view
}
else {
// elem not in view
}
}
Here, (elem_offset_top - win_scroll) represent the element position if there was no scroll. Like this, you just have to check if the element offset top is higher then the window viewport to see if it's in view or not.
Finally, you could be more precise on you calculations by adding the element height (variable already in there) because the code i just did will fire the event even if the element is visible by only 1 pixels.
Note: I just did that in five minutes so you might have to fix some of this, but this gives you a pretty darn good idea of what's going on ;)
Feel free to comment and ask questions

Find DOM elements at top and bottom of scrolling div with jQuery

I have a scrolling div containing list items. I have this boilerplate scroll event defined
$("#scrollingDiv").scroll(function(e) {
});
Inside of this scroll event function, how can I figure out which elements are at the top and bottom of the currently visible area?
You could try computing the positions of the list items with respect to the scrolling <div> and then scan the positions to see which ones match up with the scrollTop of the <div>.
Something like this perhaps:
var base = $('#scrollingDiv').offset().top;
var offs = [ ];
$('li').each(function() {
var $this = $(this);
offs.push({
offset: $this.offset().top - base,
height: $this.height()
});
});
$("#scrollingDiv").scroll(function() {
var y = this.scrollTop;
for(var i = 0; i < offs.length; ++i) {
if(y < offs[i].offset
|| y > offs[i].offset + offs[i].height)
continue;
// Entry i is at the top so do things to it.
return;
}
});
Live version (open your console please): http://jsfiddle.net/ambiguous/yHH7C/
You'd probably want to play with the fuzziness of the if to get something that works sensibly (1px visible hardly makes an element the top one) but the basic idea should be clear enough. Mixing in the height of #scrollingDiv will let you see which <li> is at the bottom.
If you have a lot of list items, then a linear search might not be what you want but you should be able to solve that without too much effort.

Javascript to turn an unordered list into multiple columns

There doesn't seem to be an easy way in (well supported) css to do this. I'm looking for a javascript solution, preferably jQuery.
I have an unordered list like this:
<ul>
<li>A</li>
<li>B</li>
<li>C</li>
<li>D</li>
<li>E</li>
...etc
</ul>
I want each column to have a height for example four items and fill vertically rather than horizontally like a css float:
A E
B F
C
D
You will want to use a combination of CSS and jQuery, but in theory it is very simple. Render a complete single list in HTML, then provide a wrapper via jQuery and split the list up as desired. The following function does just that. Be sure to use a more specific selector than just ul when actually using the script. An id would be ideal.
View demo here.
jQuery(function ($) {
var size = 4,
$ul = $("ul"),
$lis = $ul.children().filter(':gt(' + (size - 1) + ')'),
loop = Math.ceil($lis.length / size),
i = 0;
$ul.css('float', 'left').wrap("<div style='overflow: hidden'></div>");
for (; i < loop; i = i + 1) {
$ul = $("<ul />").css('float', 'left').append($lis.slice(i * size, (i * size) + size)).insertAfter($ul);
}
});
See this article:
One of the minor holy grails of XHTML
and CSS is to produce a single,
semantically logical ordered list that
wraps into vertical columns.
I’ll warn you up front. If you want to
present a list in multiple columns,
you’ll have to compromise. You can
sacrifice W3C web standards and use
deprecated markup, you can live with
markup that’s less than semantically
logical, you can tolerate a mixture of
presentation with content, you can say
goodbye to browser compatibility, or
you can use markup that’s heavy with
attributes and styling that’s heavy
with rules. Every road exacts a toll.
http://www.alistapart.com/articles/multicolumnlists/
The "best" solution is subjective, but I'd be inclined towards arbitrary classes.
Doug's solution is nice if you want to split the list up into sub lists.
Instead I chose to position the list elements without changing the dom.
This is a bit messy, basically it puts a left margin on each element which is the column number multiplied by the column width.
This will result in a staircase layout so the next step was to add some negative top margin to bring each element up to the top.
Basically this displays as a grid. I am using this for drop down menus so it worked well. Avoid using this if you need each list item to have a dynamic height. The col_height variable could be set to the height of the largest item to make the code a bit more general purpose.
var col_max_height = 6; //Max Items per column
var col_width = 200; //Pixels
var col_height = 33; //Pixels
$('.header ul li ul').each(function() {
$(this).find('li').each(function(index){
column = parseInt(index/col_max_height);
$(this).css('margin-left', column * col_width + 'px')
if(column > 0) {
$(this).css('margin-top', (index - (col_max_height * column) + 1) * -col_height + 'px').addClass('col_'+column);
}
});
});
#Keyo, thanks for your helpful answer.
Just a few modification needed to make it work on my end.
(Formula was changed, perhaps it could help someone)
var col_max_item = 2; //Max Items per column
var col_width = $('.header ul li').css('width').replace("px", ""); //Pixels, get width from CSS
var col_height = $('.header ul li').css('height').replace("px", ""); //Pixels, get height from CSS
$('.header ul').each(function() {
$(this).find('li').each(function(index){
column = parseInt(index/col_max_item);
$(this).css('margin-left', column * col_width + 'px')
if(column > 0 && (index / col_max_item) == column) {
$(this).css('margin-top', (col_max_item * col_height * -1) + 'px').addClass('col_'+column);
}
});
});
for this I use a plugin called "Easy List Splitter". here is the link:
http://www.madeincima.it/en/articles/resources-and-tools/easy-list-splitter-plugin/
Just a little different moves up the next column instead of each li.
var col_max_height = 6; //Max Items per column
var col_width = 120; //Pixels
var prevCol = 0;
$('.header ul').each(function() {
$(this).find('li').each(function(index){
column = parseInt(index/col_max_height);
$(this).css('margin-left', column * col_width + 'px')
if(prevCol != column) {
$(this).css('margin-top', '-92px').addClass('col_'+column);
prevCol = column;
} else {
$(this).css('margin-top', '0px').addClass('col_'+column);
}
});
});
You can do this really easily with the jQuery-Columns Plugin for example to split a ul with a class of .mylist you would do
$('.mylist').cols(2);
Here's a live example on jsfiddle

Categories

Resources