javascript function to vertically center element - javascript

I'm trying to write a function to vertically center elements if they have a class called "vcenter(#)". For example, vcenter1 vcenter2. It's supposed to take the element's parent's innerheight and subtract the element's innerheight then divide by 2. The value then is applied to the css as the margin-top. It doesn't work though. Please help!
$(document).ready(function(){
for (i=1; i<3; i++){
var childID = $(".vcenter" + i);
var parent = childID.parent().innerHeight();
var child = childID.innerHeight();
var marginTop = (parent - child)/2 + 'px';
$(childID).css({"margin-top", marginTop})
}
});

How about this...
http://jsfiddle.net/mVn9S/
$(document).ready(function () {
$('.vcenter').each(function () {
var parent = $(this).parent().innerHeight();
var child = $(this).innerHeight();
$(this).css({
'margin-top': ((parent - child) / 2) + 'px'
});
});
});
Have you considered using CSS3 Flexbox with a polyfill for old versions of IE? Might be less work.

Change your code to look like this:
$(document).ready(function(){
for (i=1; i<3; i++){
var childElement = $(".vcenter" + i);
var parent = childElement.parent().innerHeight();
var child = childElement.innerHeight();
var marginTop = (parent - child) / 2;
childElement.css({"margin-top": marginTop});
}
});
Notice use of ; at the end of lines - it's a good habit even in JS.
I don't know how your HTML looks but probably this could be easily generalized for all elements with .vcenter class:
$(document).ready(function(){
$('.vcenter').each(function() {
var childElement = $(this);
var parent = childElement.parent().innerHeight();
var child = childElement.innerHeight();
var marginTop = (parent - child) / 2;
childElement.css({"margin-top": marginTop});
});
});

Related

How to add a class to a each li whenever you scroll to it with jquery

I have a list with many li
I'd like to add a class to each li only when I scroll to that specific li
The issue is the class is added to every li once I scroll to only 1 of them
$(window).scroll(function(e) {
var y = $(document).scrollTop();
var h = $(window).height();
var t = $('li.product');
var length = t.length;
for(var i=1;i <= length;){
var number = 'li.product:nth-child('+i+')';
if(y + h > $(number).position().top){
$(number).addClass("animate__animated animate__fadeInDown");
}
i++;
}});
Thanks in Advance
I couldn't find what's wrong with your code so I made another version of your code. You can find it at https://codepen.io/beneji/pen/RwLQLVV.
The code uses .each instead of a for loop which is a better fit in this case.
You can adjust this code to your particular case.
$(window).scroll(function(){
const scrolling_position = $(window).scrollTop()
const window_height = $(window).height()
$("li.product").each(function(){
const product_position = $(this).position().top
if(product_position <= scrolling_position + window_height)
$(this).addClass("animate__animated animate__fadeInDown") // replace this by whatever class you want
});
})
Consider the following.
$(window).scroll(function(e) {
var y = $(document).scrollTop();
var h = $(window).height();
var t = $('li.product');
t.each(function(i, el) {
if ((y + h) > $(el).position().top) {
$(el).addClass("animate__animated animate__fadeInDown");
}
});
});
This is untested as you did not provide a Minimal, Reproducible Example.
Using .each() we can iterate each of the elements. i is the Index and el is the Element itself.

changing scroll top inside angular directive doesn't work

In my directive I wrote my logic for dynamic pagination (lazy loading), each time the user scroll to the bottom of the page I append more elements to it , this works fine but I want to to change the scroll position after that but it doesn't work.
This is my code :
link: function(scope, element) {
var usersArea = $(".usersArea");
usersArea.bind("scroll", function() {
var scrollHeight = $(this)[0].scrollHeight;
var scrollTop = $(this)[0].scrollTop;
var clientHeight = $(this)[0].clientHeight;
var downloadMore = scrollHeight - scrollTop - clientHeight < 50;
if (downloadMore) {
var childScope = scope.$new();
usersContainer = scope.displayPortion(usersContainer);
if (usersContainer) {
$compile(usersContainer)(childScope);
//This doesn't work !!
$(this)[0].scrollTop = 500;
}
}
});
}
I tried to change the scroll position using native javascript and with JQuery but nothings seem to work, any suggestions ?
Since the compile is not immediate procedure I would suggest to postpone any operations with the result of compiling. The easiest (but not the best) way is to use simple timer:
var elt = $(this)[0];
var scrollHeight = elt.scrollHeight;
var scrollTop = elt.scrollTop;
var clientHeight = elt.clientHeight;
var downloadMore = scrollHeight - scrollTop - clientHeight < 50;
if (downloadMore) {
var childScope = scope.$new();
usersContainer = scope.displayPortion(usersContainer);
if (usersContainer) {
$compile(usersContainer)(childScope);
setTimeout(function() {
elt.scrollTop = 500;
});
}
}

Jquery function should also work with other elements

I'm trying to make this function working multiple times:
Currently works only with the h1 tag
how can I make it working for the <div class="logo"> as well? I don't want to repeat the function, I need a way to make the function working for various elements.
demo: http://jsfiddle.net/33Ec8/4/
JS:
// Get the divs that should change
function displayThese() {
var $heading = $('h1');
var h1top = $heading.position().top;
var h1bottom = h1top + $heading.height();
var h1left = $heading.position().left;
var h1right = h1top + $heading.width();
var divs = $('li').filter(function () {
var $e = $(this);
var top = $e.position().top;
var bottom = top + $e.height();
var left = $e.position().left;
var right = left + $e.width();
return top > h1bottom || bottom < h1top || left > h1right || right < h1left;
});
return divs;
}
(function fadeInDiv() {
var divs = displayThese();
var elem = divs.eq(Math.floor(Math.random() * divs.length));
if (!elem.is(':visible')) {
elem.prev().remove();
elem.animate({
opacity: 1
}, Math.floor(Math.random() * 1000), fadeInDiv);
} else {
elem.animate({
opacity: (Math.random() * 1)
}, Math.floor(Math.random() * 1000), function () {
window.setTimeout(fadeInDiv);
});
}
})();
$(window).resize(function () {
// Get items that do not change
var divs = $('li').not(displayThese());
divs.css({
opacity: 0.3
});
});
Your question isn't stated very clearly, so I would strongly suggest describing what the code should do vs what it does.
That said, here is a half-blind attempt at answering what I think you want.
You could pass in the selector as a parameter to displayThese.
function displayThese(selectorString)
{
var $elementsUnderWhichNothingShouldFade = $(selectorString);
...
}
then when you call displayThese, you can pass in any complex selector you like.
var divsToChange = displayThese('h1, div.logo')
Of course, you would need to add extra logic to test whether the image elements were underneath any of the resulting $elementsUnderWhichNothingShouldFade (which is a list of elements).

Use JavaScript to alter width of a div

I have some JavaScript code and a button which already has an event/action assigned to it, and I want to add a second event to the button. Currently the relevant bit of code looks like this:
events: {onclick: "showTab('"+n+"')"},
How do I amend this code so that it also increases the 'width' property of a div with class='panel', by a fixed amount e.g. 50px?
EDIT:
I understand. Problem is I don't know how to change id, only classname. The div is constructed in JavaScript using buildDomModel as follows:
this.buildDomModel(this.elements["page_panels"],
{ tag: "div", className: "tab_panel",
id: "tab_panel",
childs: [...]}
)
But the id doesn't get changed to 'tab_panel'. HOWEVER, classname does get changed to 'tab_panel' which is why i tried to use getelementbyclass. So the div has no id and I don't know how to create one using the buildDomModel but I can give unique class. I have put the code in original post too.
This:
events: {onclick: "showTab('"+n+"'); $('div.panel').width('50px');"},
Or you might want to add below line to showTab function.
$('div.panel').width('50px');
Update:
Or you can do with vanilla javascript:
function setWidth()
{
// since you are using a class panel, means more than one div, using loop
var divs = document.getElementsByTagName('div');
for(var i = 0; i < divs.length; i++)
{
// check if this div has panel class
if (divs[i].getAttribute('class') === 'panel')
{
// set the width now
divs[i].setAttribute('width', '50px');
}
}
}
Or if you want to apply the width to just one specific div, give that div an id and use this function instead:
function setWidth()
{
var div = document.getElementById('div_id');
div.setAttribute('width', '50px');
}
And later use it like this:
events: {onclick: "showTab('"+n+"'); setWidth();"},
Or you might want to add below line to showTab function.
setWidth();
Update 2:
Ok modify the function like this:
function setWidth()
{
var divs = document.getElementsByTagName('div');
for(var i = 0; i < divs.length; i++)
{
// check if this div has panel class
if (divs[i].getAttribute('class') === 'tab_panel')
{
// get previous width
var prevWidth = getComputedWidth(divs[i]);
// set the width now
divs[i].setAttribute('width', (prevWidth + 50));
}
}
}
function getComputedWidth(theElt){
if(is_ie){
tmphght = document.getElementById(theElt).offsetWidth;
}
else{
docObj = document.getElementById(theElt);
var tmphght1 = document.defaultView.getComputedStyle(docObj, "").getPropertyValue("width");
tmphght = tmphght1.split('px');
tmphght = tmphght[0];
}
return tmphght;
}
Note that with jQuery it should be this code in all:
function setWidth(){
jQuery('.tab_panel').each(function(){
jQuery(this).attr('style', 'width:' + (jQuery(this).width() + 50));
});
}
instead of the function you can use this line of JQuery code:
$('div.tab_panel').attr('style',"width:100px");
any way if you dont want it to be JQuery then this function should work :
function setWidth() {
var divs = document.getElementsByTagName('div');
for (var i = 0; i < divs.length; i++) {
// check if this div has panel class
if (divs[i].getAttribute('class') === 'tab_panel') {
// set the style now
divs[i].setAttribute('style', 'width:100px');
}
}
}
putting width attribute to div wouldnt work, you need to set its style,
so i expect any of the code i provided to work.
oh no the one i sent early just set width to a new value
this one should fix your problem :
var x = $('div.tab_panel')[0].style.width.replace("px", "");
x = x + 50;
$('div.tab_panel').attr('style', "width:" + x + "px");
ok here is a non JQuery Version :
function setWidth() {
var divs = document.getElementsByTagName('div');
for (var i = 0; i < divs.length; i++) {
if (divs[i].getAttribute('class') === 'tab_panel') {
var x = divs[i].style.width.replace("px", "");
x = x + 50;
divs[i].setAttribute('style', 'width:' + x + 'px');
}
}
ok here it is :
JQuery:
function Button1_onclick() {
var x = $('div.tab_panel')[0].clientWidth;
x = x + 50;
$('div.tab_panel').attr('style', "width:" + x + "px");
}
non JQuert:
function setWidth() {
var divs = document.getElementsByTagName('div');
for (var i = 0; i < divs.length; i++) {
if (divs[i].getAttribute('class') === 'tab_panel') {
var x = divs[i].offsetWidth;
x = x + 50;
divs[i].setAttribute('style', 'width:' + x + 'px');
}
}
}
this should work

How to get top and left style property values in Javascript

I have a little bit of Javascript that almost works correctly. Here's the code:
function toggle(curlink) {
curlink.style.backgroundColor = curlink.style.backgroundColor == "yellow" ? "transparent" : "yellow";
var maindiv = document.getElementById("grid");
var links = maindiv.getElementsByTagName("a");
var list = "";
for (var i = 0; i < links.length; ++i) {
var link = links[i];
if (link.style.backgroundColor == "yellow") {
list += ("," + parseInt(link.style.left, 10) + "-" + parseInt(link.style.top, 10));
}
}
document.theForm.theList.value = list.substring(1);
return false;
};
window.onload = function() {
var links = document.getElementById("grid").getElementsByTagName("a");
for (var i = 0; i < links.length; ++i) {
links[i].onclick = function() { return toggle(this); }
}
};
The issue is with line #9; it only works when I specify values for the top and left style property of every link in the array. How do I get the top and left style property values (or X and Y coordinates) of each link in the array with Javascript when those values aren't given?
Also, what would the code above look like in jquery? Not that it's needed - I just want to reduce the code a little and dabble in the jquery framework (I'm a Javascript newbie).
Thanks in advance,
Dude-Dastic
link.offsetLeft and link.offsetTop. More about finding position here. They'll be positions relative to the offsetParent, but the link shows a way to get position relative to the document.
offsetParent will evaluate to the body if the parent elements are positioned statically or there's no table in the parent hierarchy. If you want a position other than body then update the parent of the links to have a non-static position, perhaps relative
I'm not familiar with JQuery so I can't help there
The jQuery might look something like this. Untested.
$(function(){
// Get all <a> descendents of #grid
var $anchors = $('#grid a');
// Bind a click handler to the anchors.
$anchors.click(function(){
var $clickedAnchor = $(this);
var coordinates = [];
// Set the background color of the anchor.
$clickedAnchor.css('background-color', $clickedAnchor.css('background-color') == 'yellow' ? 'transparent' : 'yellow');
// Loop through each anchor.
$anchors.each(function(){
var $anchor = $(this);
if ($anchor.css('background-color') == 'yellow') {
var offset = $anchor.offset();
coordinates.push(offset.left + '-' + offset.top);
// Or maybe..
// var parentOffset = $('#grid').offset();
// coordinates.push((offset.left - parentOffset.left) + '-' + (offset.top - parentOffset.top));
}
});
$('#theList').val(coordinates.join(','));
return false;
});
});

Categories

Resources