I am trying to build a toolbar that hides components from the right if there is not enough space to render them. My approach is to use refs and add up the width and render based on the condition if the total width has been overflowed. I want to get something working and go on improving it from there. It seems to work 'ok' when the screen size is decreased but not when trying to 're-render' the components when there is room. I suspect adding a display style of 'none' is causing some of the issues.
componentDidMount() {
this.littleFunction();
window.addEventListener('resize', this.littleFunction);
}
littleFunction = () => {
let sofar = 0;
for (const ref in this.refs) {
sofar += this.refs[ref].offsetWidth;
const index = ref.indexOf('test');
console.log(ref, sofar, this.input.offsetWidth);
if (sofar > this.input.offsetWidth && index === -1) {
this.refs[ref].style.display = 'none';
}
// // console.log(typeof this.refs[ref].style.display, this.refs[ref].style.display);
// if (this.refs[ref] !== this.input) {
// sofar = this.refs[ref].offsetWidth + sofar;
// }
// const index = ref.indexOf('test');
// // console.log(sofar, this.input.offsetWidth, index);
// if (sofar >= this.input.offsetWidth && index === -1) {
// this.refs[ref].style.display = 'none';
//
// this.forceUpdate();
// } else if (sofar < this.input.offsetWidth && index === -1) {
// // console.log('inhiaaa', sofar, this.input.offsetWidth);
// this.refs[ref].style.display = '';
//
// this.forceUpdate();
// }
}
}
After thinking about this for a while, i realized that if i set the style to display: 'none', the next time I try to run this logic to check how many components can fit, I am actually not getting the length back from the components that were previously set to display: 'none'. What I did was save the width of the components before applying calling the function.
componentDidMount() {
this.widths = new List();
for (const ref in this.refs) {
this.widths = this.widths.push(Map({
name: ref,
length: this.refs[ref].offsetWidth,
}));
}
this.littleFunction();
window.addEventListener('resize', this.littleFunction);
}
littleFunction = () => {
let sofar = 0;
this.widths.forEach(item => {
sofar += item.get('length');
const index = item.get('name').indexOf('test');
if (sofar > this.input.offsetWidth && index === -1) {
this.refs[item.get('name')].style.display = 'none';
// this.forceUpdate();
} else if (index === -1) {
this.refs[item.get('name')].style.display = 'inline';
// this.forceUpdate();
}
});
}
Have the toolbar to have style { width: '100%', overflow: 'hidden', whiteSpace: 'nowrap' } should give you the desired effect.
Related
I have a react application which contains a react component of publication cards. They represent a publication that has a title, some authors, a summary, date, and some other fields. I want each of the elements to have the same card size and each of the elements within the card to line up so the title sections are all the same height as the tallest title, the authors are the same height as the tallest of the authors and so on.
To do this, I have have an inner div that contains the content shouldn't change it's height and and outer div that I set to the highest clientHeight of all inner div elements.
I have a resize function that works, however only for when you drag and move the browser by resizing the window. When I click the maximize, restore, or snap the browser to the screen it ignores the height of the inner div and sets it to weird values. Ie, the rendered size of the content will be 85px in the chrome debugger, however clientWidth if I trace that value before I set it shows all of them for each of the inner divs as like 28 and so the outer div is being set to that value.
render() {
return (
<PubContainer>
<TitleSection
style={{ height: this.state.pubTitleHeight }}>
<InnerDiv className="innerPubTitleDiv">
{this.props.publicationData.header}
<SubtitleSection>
{this.props.publicationData.subtitle}
</SubtitleSection>
</InnerDiv>
</TitleSection>
</PubContainer>
);
}
SubtitleSection is a div and InnerDiv is the container that should have its height set to whatever is the value within. Here the rest of the code, along with the resize function.
componentDidUpdate() {
this.updatePublicationCardSizes();
}
componentDidMount() {
this._isMounted = true;
this.updatePublicationCardSizes();
window.addEventListener('resize', this.updatePublicationCardSizes.bind(this));
}
componentWillUnmount() {
this._isMounted = false;
window.removeEventListener('resize', this.updatePublicationCardSizes.bind(this));
}
updatePublicationCardSizes() {
this.setContainerHeightByClassName('innerPubTitleDiv', 'pubTitleHeight');
}
setContainerHeightByClassName(innerDivClassName, stateName) {
var classNameList = document.getElementsByClassName(innerDivClassName);
if (classNameList != undefined) {
var maxHeight = 0;
for (var index = 0; index < classNameList.length; index++) {
var divHeight = classNameList[index].clientHeight;
if (maxHeight < divHeight) {
maxHeight = divHeight;
}
}
if (this._isMounted) {
if (maxHeight > 0) {
if (this.state[stateName] != maxHeight) {
this.setState({
[stateName]: maxHeight
});
}
} else {
if (this.state[stateName] != '100%'){
this.setState({
[stateName]: '100%'
});
}
}
}
}
}
I've verified that resize is being called on all changes to the browser (drag, snap, restore, max, min). And again, the normal resizing by dragging the browser to change width does update and resize it correctly, it's only when I click the maximize button for example do I get the weird values. I'm trying to find out why just those cases don't work and how to make them work.
EDIT
I've refactored my code to use hooks, but I'm still getting the same issue when I click maximize/restore. Apparently the inner div clientHeight is still being calculated from a pre-render size, instead of setting it after the resize event has finished and rendered. Any ideas?
function PublicationCard(props) {
const [pubTitleHeight, setTitleHeight] = useState('100%');
useLayoutEffect(() => {
updatePublicationCardSizes();
window.addEventListener("resize", updatePublicationCardSizes);
return () => window.removeEventListener("resize", updatePublicationCardSizes);
});
const updatePublicationCardSizes = () => {
setTitleHeight(getContainerMaxHeightByClassName('innerPubTitleDiv'));
};
const getContainerMaxHeightByClassName = (innerDivClassName) => {
var classNameList = document.getElementsByClassName(innerDivClassName);
if (classNameList != undefined) {
var maxHeight = 0;
for (var index = 0; index < classNameList.length; index++) {
var divHeight = classNameList[index].clientHeight;
if (maxHeight < divHeight) {
maxHeight = divHeight;
}
}
if (maxHeight > 0) {
return maxHeight;
} else {
return '100%';
}
}
};
return (
<PubContainer>
<a href={`/publications/${props.publicationData.id}`} target="blank">
<div
style={{ height: pubTitleHeight }}>
<div className="innerPubTitleDiv">
{props.publicationData.header}
<span>
{props.publicationData.subtitle}
</span>
</div>
</div>
</a>
</PubContainer>
);
}
I can already, input the image and crop it. I tried to apply CSS filters to it, but seems the CSS filters only apply on the img tag, not the actual image.
I am using both #Alyle-cropping and ngx-image-cropper(tests). Both give to me a base64 string for the cropped image. I am able to load the cropped image to the img tag and also upload it to the database.
onCropped(e: ImgCropperEvent) {
this.croppedImage = e.dataURL;
// console.log('cropped img: ', e.dataURL);
}
onloaded(e: ImgCropperEvent) {
this.imagemOriginal = e.originalDataURL;
this.cropper.center();
console.log('img loaded', e.name);
}
onerror(e: ImgCropperErrorEvent) {
console.warn(`'${e.name}' is not a valid image`, e);
}
// Aplicar Filtros /////////////////////////////////////////////////
change(crop: Crop): void {
this.stylus = crop.nome;
this.crops.forEach(function (value) {
(value.nome === crop.nome) ? value.ehSelec = true : value.ehSelec = false;
});
// const canvas = document.getElementById('cropping'), image = document.createElement('img');
// image.src = canvas.toDataURL('image/jpeg', 1.0);
// document.body.appendChild(image);
}
enviarParanue(): void {
const ref = firebase.storage().ref(`imagens/usuarios/idTeste`).child(`nomeTeste`);
const stringa = this.removerString(this.croppedImage);
ref.put(this.base64toBlob(stringa, 'image/png')).then((snapshot) => {
// console.log('snapshot', snapshot.valueOf());
ref.getDownloadURL().then(function(downloadURL) {
console.log('File available at', downloadURL);
});
});
// ref.putString(stringa, 'base64', {contentType: 'image/png'}).then((snapshot) => {
// // console.log('snapshot', snapshot.valueOf());
// ref.getDownloadURL().then(function(downloadURL) {
// console.log('File available at', downloadURL);
// });
// });
}
removerString(stringa: string): string {
return stringa.substring(23);
}
base64toBlob(base64Data: any, contentType: any) {
contentType = contentType || '';
const sliceSize = 1024;
const byteCharacters = atob(base64Data);
const bytesLength = byteCharacters.length;
const slicesCount = Math.ceil(bytesLength / sliceSize);
const byteArrays = new Array(slicesCount);
for (let sliceIndex = 0; sliceIndex < slicesCount; ++ sliceIndex) {
const begin = sliceIndex * sliceSize;
const end = Math.min(begin + sliceSize, bytesLength);
const bytes = new Array(end - begin);
for (let offset = begin, i = 0 ; offset < end; ++i, ++offset) {
bytes[i] = byteCharacters[offset].charCodeAt(0);
}
byteArrays[sliceIndex] = new Uint8Array(bytes);
}
return new Blob(byteArrays, { type: contentType });
}
EXAMPLE OF THE CSS FILTERS:
.none {filter:none;}
.blur {filter:blur(2.5px);}
.brightness {filter:brightness(200%);}
.contrast {filter:contrast(200%);}
.drop-shadow {filter:drop-shadow(8px 8px 10px gray);}
.grayscale {filter:grayscale(100%);}
.hue-rotate {filter:hue-rotate(90deg);}
.invert {filter:invert(100%);}
.opacity {filter:opacity(30%);}
.saturate {filter:saturate(8);}
.sepia {filter:sepia(100%);}
.contrast-brightness {filter:contrast(200%) brightness(150%);}
Problem is... I don't know how to apply the CSS filters to the image to upload the cropped with the effects(sepia, contrast, etc).
I tried to get the img src and convert it to Blob, but didn't work.
I ended up saving in the database a string with the name of the filter. So I apply the filter when I load the image. A good side of it, is that I can change the filter whenever I want.
I have a side menu and when it's open, the body can be partially seen. My side menu might be long so you could scroll on it. But when the menu is at the bottom you then scroll on the body, and I don't want this behaviour.
Similar to Scrolling only content div, others should be fixed but I'm using React. Other content should be scrollable when my side menu is closed. Think of the content as side menu in the example in the link. So far I'm using the same technique provided by that answer but it's ugly (kinda jQuery):
preventOverflow = (menuOpen) => { // this is called when side menu is toggled
const body = document.getElementsByTagName('body')[0]; // this should be fixed when side menu is open
if (menuOpen) {
body.className += ' overflow-hidden';
} else {
body.className = body.className.replace(' overflow-hidden', '');
}
}
// css
.overflow-hidden {
overflow-y: hidden;
}
What should I do with Reactjs?
You should make a meta component in react to change things on the body as well as changing things like document title and things like that. I made one a while ago to do that for me. I'll add it here.
Usage
render() {
return (
<div>
<DocumentMeta bodyClasses={[isMenuOpen ? 'no-scroll' : '']} />
... rest of your normal code
</div>
)
}
DocumentMeta.jsx
import React from 'react';
import _ from 'lodash';
import withSideEffect from 'react-side-effect';
var HEADER_ATTRIBUTE = "data-react-header";
var TAG_NAMES = {
META: "meta",
LINK: "link",
};
var TAG_PROPERTIES = {
NAME: "name",
CHARSET: "charset",
HTTPEQUIV: "http-equiv",
REL: "rel",
HREF: "href",
PROPERTY: "property",
CONTENT: "content"
};
var getInnermostProperty = (propsList, property) => {
return _.result(_.find(propsList.reverse(), property), property);
};
var getTitleFromPropsList = (propsList) => {
var innermostTitle = getInnermostProperty(propsList, "title");
var innermostTemplate = getInnermostProperty(propsList, "titleTemplate");
if (innermostTemplate && innermostTitle) {
return innermostTemplate.replace(/\%s/g, innermostTitle);
}
return innermostTitle || "";
};
var getBodyIdFromPropsList = (propsList) => {
var bodyId = getInnermostProperty(propsList, "bodyId");
return bodyId;
};
var getBodyClassesFromPropsList = (propsList) => {
return propsList
.filter(props => props.bodyClasses && Array.isArray(props.bodyClasses))
.map(props => props.bodyClasses)
.reduce((classes, list) => classes.concat(list), []);
};
var getTagsFromPropsList = (tagName, uniqueTagIds, propsList) => {
// Calculate list of tags, giving priority innermost component (end of the propslist)
var approvedSeenTags = {};
var validTags = _.keys(TAG_PROPERTIES).map(key => TAG_PROPERTIES[key]);
var tagList = propsList
.filter(props => props[tagName] !== undefined)
.map(props => props[tagName])
.reverse()
.reduce((approvedTags, instanceTags) => {
var instanceSeenTags = {};
instanceTags.filter(tag => {
for(var attributeKey in tag) {
var value = tag[attributeKey].toLowerCase();
var attributeKey = attributeKey.toLowerCase();
if (validTags.indexOf(attributeKey) == -1) {
return false;
}
if (!approvedSeenTags[attributeKey]) {
approvedSeenTags[attributeKey] = [];
}
if (!instanceSeenTags[attributeKey]) {
instanceSeenTags[attributeKey] = [];
}
if (!_.has(approvedSeenTags[attributeKey], value)) {
instanceSeenTags[attributeKey].push(value);
return true;
}
return false;
}
})
.reverse()
.forEach(tag => approvedTags.push(tag));
// Update seen tags with tags from this instance
_.keys(instanceSeenTags).forEach((attr) => {
approvedSeenTags[attr] = _.union(approvedSeenTags[attr], instanceSeenTags[attr])
});
instanceSeenTags = {};
return approvedTags;
}, []);
return tagList;
};
var updateTitle = title => {
document.title = title || document.title;
};
var updateBodyId = (id) => {
document.body.setAttribute("id", id);
};
var updateBodyClasses = classes => {
document.body.className = "";
classes.forEach(cl => {
if(!cl || cl == "") return;
document.body.classList.add(cl);
});
};
var updateTags = (type, tags) => {
var headElement = document.head || document.querySelector("head");
var existingTags = headElement.querySelectorAll(`${type}[${HEADER_ATTRIBUTE}]`);
existingTags = Array.prototype.slice.call(existingTags);
// Remove any duplicate tags
existingTags.forEach(tag => tag.parentNode.removeChild(tag));
if (tags && tags.length) {
tags.forEach(tag => {
var newElement = document.createElement(type);
for (var attribute in tag) {
if (tag.hasOwnProperty(attribute)) {
newElement.setAttribute(attribute, tag[attribute]);
}
}
newElement.setAttribute(HEADER_ATTRIBUTE, "true");
headElement.insertBefore(newElement, headElement.firstChild);
});
}
};
var generateTagsAsString = (type, tags) => {
var html = tags.map(tag => {
var attributeHtml = Object.keys(tag)
.map((attribute) => {
const encodedValue = HTMLEntities.encode(tag[attribute], {
useNamedReferences: true
});
return `${attribute}="${encodedValue}"`;
})
.join(" ");
return `<${type} ${attributeHtml} ${HEADER_ATTRIBUTE}="true" />`;
});
return html.join("\n");
};
var reducePropsToState = (propsList) => ({
title: getTitleFromPropsList(propsList),
metaTags: getTagsFromPropsList(TAG_NAMES.META, [TAG_PROPERTIES.NAME, TAG_PROPERTIES.CHARSET, TAG_PROPERTIES.HTTPEQUIV, TAG_PROPERTIES.CONTENT], propsList),
linkTags: getTagsFromPropsList(TAG_NAMES.LINK, [TAG_PROPERTIES.REL, TAG_PROPERTIES.HREF], propsList),
bodyId: getBodyIdFromPropsList(propsList),
bodyClasses: getBodyClassesFromPropsList(propsList),
});
var handleClientStateChange = ({title, metaTags, linkTags, bodyId, bodyClasses}) => {
updateTitle(title);
updateTags(TAG_NAMES.LINK, linkTags);
updateTags(TAG_NAMES.META, metaTags);
updateBodyId(bodyId);
updateBodyClasses(bodyClasses)
};
var mapStateOnServer = ({title, metaTags, linkTags}) => ({
title: HTMLEntities.encode(title),
meta: generateTagsAsString(TAG_NAMES.META, metaTags),
link: generateTagsAsString(TAG_NAMES.LINK, linkTags)
});
var DocumentMeta = React.createClass({
propTypes: {
title: React.PropTypes.string,
titleTemplate: React.PropTypes.string,
meta: React.PropTypes.arrayOf(React.PropTypes.object),
link: React.PropTypes.arrayOf(React.PropTypes.object),
children: React.PropTypes.oneOfType([
React.PropTypes.object,
React.PropTypes.array
]),
bodyClasses: React.PropTypes.array,
},
render() {
if (Object.is(React.Children.count(this.props.children), 1)) {
return React.Children.only(this.props.children);
} else if (React.Children.count(this.props.children) > 1) {
return (
<span>
{this.props.children}
</span>
);
}
return null;
},
});
DocumentMeta = withSideEffect(reducePropsToState, handleClientStateChange, mapStateOnServer)(DocumentMeta);
module.exports = DocumentMeta;
This component could probably be changed a little for your case (withSideEffect is used for both client and server side rendering... if you arent using server side rendering then its probably not completely necessary) but the component will work on client side rendering if you would like to use it there as well.
ReactJS doesn't have direct access to the <body> element, and that's the element that needs to have its overflow-y style changed. So while what you're doing isn't perhaps the prettiest code, it's not entirely wrong either.
The only real suggestion I'd give is (shudder) using inline styles on the body instead of a classname so as to avoid having to introduce the CSS declaration. As long as your menu is the only thing responsible for updating the overflow-y attribute, there's no reason you can't use an inline style on it. Mashing that down with the ?: operator results in fairly simple code:
body.style.overflowY = menuOpen ? "hidden" : "";
And then you can just delete the .overflow-hidden class in its entirety.
If for some reason multiple things are managing the overflow state of the body, you might want to stick with classnames and assign a unique one for each thing managing it, something like this:
if (menuOpen) {
body.className += ' menu-open';
}
else {
// Use some tricks from jQuery to remove the "menu-open" class more elegantly.
var className = " " + body.className + " ";
className = className.replace(" overflow-hidden ", " ").replace(/\s+/, " ");
className = className.substr(1, className.length - 2);
}
CSS:
body.menu-open {
overflow-y: hidden;
}
I'm working on a website for a school project, I'm using a template called quantua. If you go to live demo of the template ( http://www.templatesjoomla.net/index.php/joomla3-x/244-quantua-joomla-3-x.html ), you can see that when resizing the browser window the image shrinks so much that a black background appears. I don't want it to do that, how can the resizing be achived like on this (http://www.websitetemplatesonline.com/free-template/progress-business.html) template? I played with css quite a bit, but i failed, so I guess it has to do with javascript?
heres the javascript code
(function($) {
var NivoSlider = function(element, options){
// Defaults are below
var settings = $.extend({}, $.fn.nivoSlider.defaults, options);
// Useful variables. Play carefully.
var vars = {
currentSlide: 0,
currentImage: '',
totalSlides: 0,
running: false,
paused: false,
stop: false,
controlNavEl: false
};
// Get this slider
var slider = $(element);
slider.data('nivo:vars', vars).addClass('nivoSlider');
// Find our slider children
var kids = slider.children();
kids.each(function() {
var child = $(this);
var link = '';
if(!child.is('img')){
if(child.is('a')){
child.addClass('nivo-imageLink');
link = child;
}
child = child.find('img:first');
}
// Get img width & height
var childWidth = (childWidth === 0) ? child.attr('width') : child.width(),
childHeight = (childHeight === 0) ? child.attr('height') : child.height();
if(link !== ''){
link.css('display','none');
}
child.css('display','none');
vars.totalSlides++;
});
// If randomStart
if(settings.randomStart){
settings.startSlide = Math.floor(Math.random() * vars.totalSlides);
}
// Set startSlide
if(settings.startSlide > 0){
if(settings.startSlide >= vars.totalSlides) { settings.startSlide = vars.totalSlides - 1; }
vars.currentSlide = settings.startSlide;
}
// Get initial image
if($(kids[vars.currentSlide]).is('img')){
vars.currentImage = $(kids[vars.currentSlide]);
} else {
vars.currentImage = $(kids[vars.currentSlide]).find('img:first');
}
// Show initial link
if($(kids[vars.currentSlide]).is('a')){
$(kids[vars.currentSlide]).css('display','block');
}
// Set first background
var sliderImg = $('<img class="nivo-main-image" src="#" />');
sliderImg.attr('src', vars.currentImage.attr('src')).show();
slider.append(sliderImg);
// Detect Window Resize
$(window).resize(function() {
slider.children('img').width(slider.width());
sliderImg.attr('src', vars.currentImage.attr('src'));
sliderImg.stop().height('auto');
$('.nivo-slice').remove();
$('.nivo-box').remove();
});
//Create caption
slider.append($('<div class="nivo-caption"></div>'));
// Process caption function
var processCaption = function(settings){
var nivoCaption = $('.nivo-caption', slider);
if(vars.currentImage.attr('title') != '' && vars.currentImage.attr('title') != undefined){
var title = vars.currentImage.attr('title');
if(title.substr(0,1) == '#') title = $(title).html();
if(nivoCaption.css('display') == 'block'){
setTimeout(function(){
nivoCaption.html(title);
}, settings.animSpeed);
} else {
nivoCaption.html(title);
nivoCaption.stop().fadeIn(settings.animSpeed);
}
} else {
nivoCaption.stop().fadeOut(settings.animSpeed);
}
}
//Process initial caption
processCaption(settings);
// In the words of Super Mario "let's a go!"
var timer = 0;
if(!settings.manualAdvance && kids.length > 1){
timer = setInterval(function(){ nivoRun(slider, kids, settings, false); }, settings.pauseTime);
}
// Add Direction nav
if(settings.directionNav){
slider.append('<div class="nivo-directionNav"><a class="nivo-prevNav">'+ settings.prevText +'</a><a class="nivo-nextNav">'+ settings.nextText +'</a></div>');
// Hide Direction nav
if(settings.directionNavHide){
$('.nivo-directionNav', slider).hide();
slider.hover(function(){
$('.nivo-directionNav', slider).show();
}, function(){
$('.nivo-directionNav', slider).hide();
});
}
$('a.nivo-prevNav', slider).live('click', function(){
if(vars.running) { return false; }
clearInterval(timer);
timer = '';
vars.currentSlide -= 2;
nivoRun(slider, kids, settings, 'prev');
});
$('a.nivo-nextNav', slider).live('click', function(){
if(vars.running) { return false; }
clearInterval(timer);
timer = '';
nivoRun(slider, kids, settings, 'next');
});
}
// Add Control nav
if(settings.controlNav){
vars.controlNavEl = $('<div class="nivo-controlNav"></div>');
slider.after(vars.controlNavEl);
for(var i = 0; i < kids.length; i++){
if(settings.controlNavThumbs){
vars.controlNavEl.addClass('nivo-thumbs-enabled');
var child = kids.eq(i);
if(!child.is('img')){
child = child.find('img:first');
}
if(child.attr('data-thumb')) vars.controlNavEl.append('<a class="nivo-control" rel="'+ i +'"><img src="'+ child.attr('data-thumb') +'" alt="" /></a>');
} else {
vars.controlNavEl.append('<a class="nivo-control" rel="'+ i +'">'+ (i + 1) +'</a>');
}
}
//Set initial active link
$('a:eq('+ vars.currentSlide +')', vars.controlNavEl).addClass('active');
$('a', vars.controlNavEl).bind('click', function(){
if(vars.running) return false;
if($(this).hasClass('active')) return false;
clearInterval(timer);
timer = '';
sliderImg.attr('src', vars.currentImage.attr('src'));
vars.currentSlide = $(this).attr('rel') - 1;
nivoRun(slider, kids, settings, 'control');
});
}
//For pauseOnHover setting
if(settings.pauseOnHover){
slider.hover(function(){
vars.paused = true;
clearInterval(timer);
timer = '';
}, function(){
vars.paused = false;
// Restart the timer
if(timer === '' && !settings.manualAdvance){
timer = setInterval(function(){ nivoRun(slider, kids, settings, false); }, settings.pauseTime);
}
});
}
// Event when Animation finishes
slider.bind('nivo:animFinished', function(){
sliderImg.attr('src', vars.currentImage.attr('src'));
vars.running = false;
// Hide child links
$(kids).each(function(){
if($(this).is('a')){
$(this).css('display','none');
}
});
// Show current link
if($(kids[vars.currentSlide]).is('a')){
$(kids[vars.currentSlide]).css('display','block');
}
// Restart the timer
if(timer === '' && !vars.paused && !settings.manualAdvance){
timer = setInterval(function(){ nivoRun(slider, kids, settings, false); }, settings.pauseTime);
}
// Trigger the afterChange callback
settings.afterChange.call(this);
});
You are looking in the wrong place. use firebug to inspect and know which css file is being used. the file is default.css. Line 159. Thats what you should be playing with. this is what it looks like
.nivoSlider {
float: left;
position: relative;
width: 100%;
height: 480px;
overflow: hidden;
background: #000
this is the block of code that affects the presentation of the navigation bar. but to eradicate the blackness down there, you can use this close fix
change the property height of the nivoslider class to auto on line 159
change the backgroud property of the navigation class from transparent to black on line 296
change the margin-top property of the id menu class to 316px on line 285
this is not guaranteed to not distort especially the last point. but keep trying.
I started the first question here: but it was very hard to make the effect for each single page I had, So I thought if I made the div that I wanted to make fixed not fixed to the screen scroll
Very Hard to compute heights with pure math and it doesn't work ultimately as you need to modify the calculation for every single page
Here is the code :
<script >window.addEventListener("scroll",function() {
if(window.scrollY >= 148) {
document.getElementById('main_nav').style.position = 'absolute';
document.getElementById('main_nav').style.bottom = '65%';
}
if(window.scrollY <= 148){
document.getElementById('main_nav').style.position = 'fixed';
document.getElementById('main_nav').style.top = '42%';
}
});</script>
so to get things clear That piece of code depends on scroll height of screen.
I need to apply the following effect :
when the page loads the main_nav div is position:fixed.
On scrolling down
when main_nav is above some div by: say 20px it should stop position:fixed.
It should stand still at it's last place.
On scrolling up again.
It should restore the position fixed again .
"This creates the float effect till some point"
Someone I know gave me the link for this question and a js code and told me to past it here
so here its if it is not relevant to the subject please let me knw
Someone I know gave me the link for this question and a js code and told me to past it here
so here its if it is not relevant to the subject please let me know and I will delete it
/* ===========================================================
* fixate.js v1
* Use:
* Inspired by the original jquery sticky scroller
* ========================================================== */
!function ($) {
"use strict"; // jshint ;_;
/* FIXATE PUBLIC CLASS DEFINITION
* =============================== */
var Fixate = function (element, options) {
this.init(element, options);
}
Fixate.prototype = {
constructor: Fixate
, init: function (element, options) {
var self, opts;
this.$element = $(element);
opts = this.options = this.getOptions(options);
this.zindex = this.$element.css('z-index');
this.$window = $(window);
this.$doc = $(document);
this.$bottomCap = opts.bottomCapEl ? $(opts.bottomCapEl) : false;
this.$topCap = opts.topCapEl ? $(opts.topCapEl) : false;
this.bottomOffset = opts.windowInset.bottom || 0;
this.topOffset = opts.windowInset.top || 0;
this.top = this.$element.offset().top - parseFloat(this.$element.css('margin-top').replace(/auto/, 0)) - this.topOffset;
this.eto = this.$element.offset().top;
this.origTop = this.$element.css('top');
this.origBottom = this.$element.css('bottom');
this.z = (this.zindex === '0' || this.zindex === 'auto') ? opts.zindex : this.zindex;
this.bh = (this.$bottomCap) ? this.$bottomCap.outerHeight(true) : 0;
self = this;
this.$window.on('scroll', function (e) {
self.fixate();
});
this.$doc.on('DOMNodeInserted DOMNodeRemoved', function(e){
//Called when elements are added or removed from DOM
self.fixate();
});
}
, getOptions: function (options) {
options = $.extend({}, $.fn['fixate'].defaults, options, this.$element.data());
return options;
}
, fixate: function(){
var s = this.$window.scrollTop()
, h = this.$element.outerHeight(true);
// Calc offset onscroll to get most updated results - incasse ajaxed els come in
this.bco = (this.$bottomCap) ? this.$bottomCap.offset().top : 0;
this.tco = (this.$topCap) ? this.$topCap.offset().top + this.$topCap.outerHeight(true) : 0;
this.dh = this.$doc.height();
if(this.options.windowEdge === 'top'){
this.fixToTop(s, h);
} else {
this.fixToBottom(s, h);
}
}
, fixToTop: function (s, h) {
var bco = this.bco
, to = this.topOffset
, eto = this.eto
, bo = this.bottomOffset
, point = bco - h - bo - to;
if (s >= this.top) {
this.$element.css({
'position': 'fixed',
'top': to,
'z-index': this.z
});
this.fixTouchDevice();
// Bottom cap calc -check cpu factor
if (s >= point) {
this.$element.css({
'top': Math.round(point - this.top + parseFloat(this.origTop)),
'position': 'absolute'
});
}
} else {
this.$element.css({
'position': '',
'top': this.origTop,
'z-index': this.zindex
});
}
}
, fixToBottom: function (s, h) {
var bco = this.bco
, to = this.topOffset
, eto = this.eto
, bo = this.bottomOffset;
if (s >= ( bco - h - bo - to - this.top) ) {
this.$element.css({
'bottom': Math.round(this.dh-(bco - bo)),
'position': 'absolute'
});
this.fixTouchDevice();
} else {
this.$element.css({
'position': 'fixed',
'bottom': bo,
'z-index': this.z
});
}
}
, fixTouchDevice: function(){
//stick the footer at the bottom of the page if we're on an iPad/iPhone due to viewport/page bugs in mobile webkit
if(navigator.platform == 'iPad' || navigator.platform == 'iPhone' || navigator.platform == 'iPod') {
this.$element.css("position", "static");
}
}
}
/* FIXATE PLUGIN DEFINITION
* ========================= */
$.fn.fixate = function (option) {
return this.each(function () {
var $this = $(this),
data = $this.data('fixate'),
options = typeof option == 'object' && option;
if (!data) $this.data('fixate', (data = new Fixate(this, options)));
if (typeof option == 'string') data[option]();
})
}
$.fn.fixate.Constructor = Fixate;
$.fn.fixate.defaults = {
windowInset: {
top: 0,
bottom: 0
}
, windowEdge: 'top'
, bottomCapEl: 'footer'
, topCapEl: 'header'
, zindex: 5
};
}(window.jQuery);