Opening Div at a specific position - javascript

I need to open a div at a specific location on the page. When I focus on a textbox the div should be opened(made visible). I am able to do this part. The problem is it opens right underneath the textbox and when there is no scroll on the page, it creates one. I need help in showing the div above the textbox when there is more space on upper half of the page then the lower half of the page. Here is the JSFiddle I have created and if someone can edit it, it would be of too much help to me.
And this is how I am opening the div:
function openDIV(activatorCtl) {
var leftpos = 0;
var toppos = 0;
var sScrollTop = getScrollTop;
var aTag = activatorCtl;
do {
aTag = aTag.offsetParent;
sScrollTop = (aTag.scrollTop > sScrollTop) ? aTag.scrollTop : sScrollTop;
leftpos += aTag.offsetLeft;
toppos += aTag.offsetTop;
} while (aTag.tagName != 'BODY');
document.getElementById("divDetails").style.left = leftpos + "px";
document.getElementById("divDetails").style.top = toppos + 20 + "px";
document.getElementById("divDetails").style.zIndex = "999";
document.getElementById("divDetails").style.visibility = "visible";
}

You mean like this?
https://jsfiddle.net/36vdoaqo/3/
I added an if for when the toppos is bigger than 250 (your divs height)
if(toppos <= 250)
Another tip:
You use this 4 times in a row:
document.getElementById("divDetails")
save this element in an variable to get shorter statements like:
var detailsDiv = document.getElementById("divDetails");
detailsDiv.style.left = leftpos + "px";
detailsDiv.style.zIndex = "999";
EDIT: i did not save the jsfiddle properly.

Related

How to check bottom of child div touching parent bottom

i'm trying to change position of a child element(with varying height based on text) using range input,i would like to stop applying top position once the child div touches the bottom of the parent having fixed height.
$('#change_position').on('input', function () {
var val = +$(this).val(),
ScrSize = parseInt($('.screen').css('height')),
Stop = $('.screentip').offset().top,
h = parseInt($('.screentip').css('height')),
tofsset = Stop - h;
if (tofsset < ScrSize) {
$('.screentip').css('top', val + "%");
}
});
The height you are expecting jQuery to return is actually a string with the ending "px". You can use the function .height(). This will return you the height of the element as integer. I have tried a slightly modiefied version of your code:
$('#input').on('input', function () {
var val = parseInt($(this).val()),
ScrSize = parseInt($('#container').height()),
TxtSize = parseInt($("#text").height()),
Stop = ScrSize - TxtSize,
valInPixel = ScrSize * val / 100;
if (valInPixel < Stop) {
$('#text').css('top', val + "%");
}
else
{
$("#text").css("top", Stop + "px");
}
});
The else part will position your element to the bottom, if the number exceeds the frame. You may also have to be aware of padding and margin. This could also lead to mispositioning.
Hope this helps.

How to scroll to the selected form field when key board shown in android app with javascript or jQuery?

I used this code to window scroll top in android app. but its scrolling total body. not till to selected form field. I want scroll till to selected form field.
here is my code
var is_keyboard = false;
var is_landscape = false;
var initial_screen_size = window.innerHeight;
window.addEventListener("resize", function() {
var currentHeight = window.innerHeight;
is_keyboard = (window.innerHeight < initial_screen_size);
is_landscape = (screen.height < screen.width);
var keyboardSize = (initial_screen_size - currentHeight);
if (keyboardSize > 0) {
alert("Keyboard is shown! Size is: " + keyboardSize);
} else {
alert("Keyboard is closed!");
}
alert('Screen resized. currentHeight: ' + currentHeight + " - OriginalHeight: " + initial_screen_size);
}, false);
To scroll to selected field you need to set a class or id on that element on capturing the event you need to check the flag on that element and then
find the offset and scroll the document to it.
Hope this helps
if (scroll_flag == ' scroll1'){
var fooOffset = $('#gift').offset(),
destination = fooOffset.top;
console.log(destination);
$(document).scrollTop(destination);
}

Menu items changing color according to position of element

My page is divided into three sections and each section can be accessed by respective menu item. I am trying to achieve this in Javascript: when the user has reached any of the sections by scrolling, the font color of respective menu item should change.
Here I call the function:
<body onscroll="detectScroll(); showPosition();">
This is the function that detects scrolling and changes some items accordingly. It's working fine:
function detectScroll() {
var header = document.querySelector(".headerOrig"),
header_height = getComputedStyle(header).height.split('px')[0],
header_class = "changeHeader",
logo = document.getElementById("logo")
;
if( window.pageYOffset > (parseInt(header_height) + 500)) {
header.classList.add(header_class);
logo.src = "images/logo2.png";
}
if( window.pageYOffset < (parseInt(header_height) + 500)) {
header.classList.remove(header_class);
logo.src = "images/logo1.png";
}
}
This JS function returns the position of an element. Works fine as well:
function getPosition(element) {
var xPosition = 0;
var yPosition = 0;
while(element) {
xPosition += (element.offsetLeft - element.scrollLeft + element.clientLeft);
yPosition += (element.offsetTop - element.scrollTop + element.clientTop);
element = element.offsetParent;
}
return { x: xPosition, y: yPosition };
}
And, finally, this is the JS function that is being called when scrolling:
function showPosition() {
var myElement = document.getElementById("posBIKES");
var position = getPosition(myElement);
var bike = document.getElementById("bikesMenu");
//alert("The element is located at: " + position.x + ", " + position.y);
if(window.pageYOffset < position.y) {
window.getElementById("bikesMenu").classList.remove("changeMenu");
}
if(window.pageYOffset > position.y) {
window.getElementById("bikesMenu").classList.add("changeMenu");
}
}
The problem is everything works fine until I try to add or remove the class to the item selected (the last function). Any other statement works fine, for example, I tried putting alert("something"); in both conditions and both worked as desired. Whats wrong with adding and removing classes then?
And yes, I have checked the corresponding names and IDs of everything like million times, so theres no issue with that.
Any help is more than appreciated.
Thanks

I am creating multiple sliders in a page... but not getting the correct stop position if the number of slides are different from each other

I am creating multiple sliders in a page... but not getting the correct stop position if the number of slides are different from each other..
If I keep the number of slides same it works well..
But I need different number of slides in sliders...
$(document).ready(function(){
$('.myslider-wrapper').each(function(){
// thumbSlide
var countSlider = $('.thumbSlide').length;
if((".thumbSlide").length){
// Declare variables
var totalImages = $(".thumbSlide > li").length,
imageWidth = $(".thumbSlide > li:first").outerWidth(true),
totalWidth = imageWidth * totalImages,
visibleImages = Math.round($(".thumbSlide-wrap").width() / imageWidth),
visibleWidth = visibleImages * imageWidth,
stopPosition = (visibleWidth - totalWidth/countSlider);
$(".thumbSlide").width(totalWidth+10);
$(".thumbSlide-prev").click(function(){
var parentMove = $(this).parent().prev('.thumbSlide');
if(parentMove.position().left < 0 && !$(".thumbSlide").is(":animated")){
parentMove.animate({left : "+=" + imageWidth + "px"});
}
return false;
});
$(".thumbSlide-next").click(function(){
var parentMove = $(this).parent().prev('.thumbSlide');
if(parentMove.position().left > stopPosition && !$(".thumbSlide").is(":animated")){
parentMove.animate({left : "-=" + imageWidth + "px"});
}
return false;
});
}
});
});
here is jsFiddle URL:
http://jsfiddle.net/mufeedahmad/GLSqS/
You iterate through all sliders correctly by doing $('.myslider-wrapper').each(), but then you do some stuff with $('.thumbSlide') that should be $('.thumbSlide', this).
$('.thumbSlide') will select all elements on the page with that class, while $('.thumbSlide', this) within the each callback will only select the element in that particular wrapper.
Edit: fixed your jsfiddle with this solution: http://jsfiddle.net/GLSqS/1/

foldable div between a max-height its original text height

Is there an easy way (in pure javascript) to fold a div between a setted max-height and the height of its text?
In detail, I want to load a div with a preset height (40 pixels for example), and show a "show more" button, so when you click on it the div sets to the height of the text inside it (80px for example). And when you click again you set the div's height to its initial height (40 pixels).
A visual example would be something like this:
Initial state (40 pixels)
The text of the div
would be something like
this, so when the button
show more info...
if you click on "show more info" you get to this state (80 pixels)
The text of the div
would be something like
this, so when te button
is pressed..
it shows the remaining text
;)
show less info...
if you click on "show less info" you get to the previos state (40 pixels)
I've tried with height / max-height and clientHeight, but when you set the height property value you override the clientHeight one.
Thanks in advance. If the solution is too complex, don't hesitate to answer.
You might want to take a look to this tutorial: http://papermashup.com/simple-jquery-showhide-div/
An easy solution to solve this is just using the max-height property.
You can set:
div.style.maxHeight = 40; //initial state
if the button is pressed:
div.style.maxHeight = 80; //final state (set a value bigger than the text is going to be)
if pressed again:
div.style.maxHeight = 40; //initial state again
The problem of this solution is that you don't really know the real text-size, so if you set a max-height smaller than the text size, it would'n work properly. But for me solves the issue.
Thanks, and hope this helps to somebody else.
One possibly overly-complicated solution:
$('p').each(
function() {
var that = $(this);
that.attr('data-fullheight', that.height());
that.height(that.height() / 2);
that.closest('div').append('<a src="#" class="readmore">Read more</a>');
});
$('div').on('click', 'a.readmore', function(e) {
var p = $(this)
.closest('div')
.find('p[data-fullheight]'),
full = p.attr('data-fullheight');
p.animate({
'height' : full == p.height() ? full/2 : full
},200)
});​
Which assumes the following HTML (albeit the div id isn't necessary):
<div id="text">
<p>...text...</p>
</div>
​JS Fiddle demo.
Just because I thought that last one wasn't over-complicated enough, I thought I'd post this (plain-JavaScript!) solution as well:
var readmores = [];
function heights(el) {
if (!el) {
return false;
}
else {
var h = parseInt(window.getComputedStyle(el, null).height, 10),
moreLess = document.createElement('a'),
text = document.createTextNode('Read more'),
parent = el.parentNode;
readmores.push(moreLess);
moreLess.src = '#';
moreLess.className = 'readmore';
moreLess.appendChild(text);
parent.insertBefore(moreLess, el.nextSibling);
el.setAttribute('data-fullheight', h);
el.style.height = Math.floor(h / 2) + 'px';
}
}
function toggleHeight(el) {
if (!el) {
return false;
}
else {
var full = el.getAttribute('data-fullheight'),
curHeight = parseInt(el.style.height, 10);
el.style.height = full == curHeight ? Math.floor(full / 2) + 'px' : full + 'px';
}
}
function toggleText(el) {
if (!el) {
return false;
}
else {
var text = el.firstChild.nodeValue;
el.firstChild.nodeValue = text == 'Read more' ? 'Read less' : 'Read more';
}
}
var paras = document.getElementsByTagName('p');
for (var i = 0, len = paras.length; i < len; i++) {
var cur = paras[i];
heights(cur);
}
for (var i=0, len=readmores.length; i<len; i++){
readmores[i].onclick = function(){
toggleHeight(this.previousElementSibling);
toggleText(this);
}
}
​JS Fiddle demo.
This works (in Chrome 21), but makes absolutely no allowance for IE for which it will need to be amended some.

Categories

Resources