Make a splitter very thin and grab it - javascript

I want to make a draggle splitter between 2 panels. The following is a working version.
Now, I want to make the width of handle as thin as possible (less than 0.1px?), so there is no way to make the width (appear) smaller than 1px?
Additionally, when the splitter is thin, it is hard to select by the mouse. Is there a way to make a splitter easy to grab?
Taking JSBin as example, how did they manage to realise the splitters among the panels?
(function($) {
$.fn.drags = function(opt) {
opt = $.extend({
handle: "",
cursor: "ew-resize",
min: 10
}, opt);
if (opt.handle === "") {
var $el = this;
} else {
var $el = this.find(opt.handle);
}
var priorCursor = $('body').css('cursor');
return $el.css('cursor', opt.cursor).on("mousedown", function(e) {
priorCursor = $('body').css('cursor');
$('body').css('cursor', opt.cursor);
if (opt.handle === "") {
var $drag = $(this).addClass('draggable');
} else {
var $drag = $(this).addClass('active-handle').parent().addClass('draggable');
}
var z_idx = $drag.css('z-index'),
drg_h = $drag.outerHeight(),
drg_w = $drag.outerWidth(),
pos_y = $drag.offset().top + drg_h - e.pageY,
pos_x = $drag.offset().left + drg_w - e.pageX;
var mouseMove = function(e) {
var prev = $('.draggable').prev();
var next = $('.draggable').next();
var total = prev.outerWidth() + next.outerWidth();
var totalPercentage = parseFloat(prev.css('flex')) + parseFloat(next.css('flex'));
var offset = prev.offset();
if(offset){
var leftPercentage = ((e.pageX - offset.left - drg_w / 2) / total) * totalPercentage;
var rightPercentage = totalPercentage - leftPercentage;
if (leftPercentage * 100 < opt.min || rightPercentage * 100 < opt.min) {
return;
}
prev.css('flex', leftPercentage.toString());
next.css('flex', rightPercentage.toString());
}
}
$drag.css('z-index', 1000).parent().on("mousemove", mouseMove).on("mouseup", function() {
$(this).off("mousemove", mouseMove).off("mouseup");
$('body').css('cursor', priorCursor);
$('.draggable').removeClass('draggable').css('z-index', z_idx);
});
e.preventDefault(); // disable selection
});
}
})(jQuery);
$('.handle').drags();
.flex-box {
display: flex;
width: 100%;
margin: 0;
height: 300px;
}
.flex-box .col {
border: 1px solid grey;
flex: 0.33;
padding: 12px;
overflow-y: auto;
overflow-x: hide;
}
.handle {
width: 1px;
text-align: center;
background: grey;
transition: all ease-in 0.1s;
}
.draggable {
background: grey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="flex-box">
<div class="col">
<p>Pellentesque ...</p>
</div>
<div class="handle"></div>
<div class="col">
<p>Pellentesque ...</p>
</div>
</div>

If you'd like the handle to appear thinner try applying a negative value to the right "col" e.g. margin-left: -2px; so it overlaps the left "col" border on the left of it. I don't think you can make the width "appear" as 0.1px. Firefox is the only browser that renders such value. (https://css-tricks.com/forums/topic/0-1px-borders/)
.flex-box .col:last-child {
margin-left: -2px;
}
//raise handle layer to top
.handle {
.....
z-index: 9999;
}
Hope this helps...
*Edit:
This is the closest I could get to your request:
.flex-box {
display: flex;
width: 100%;
margin: 0;
height: 300px;
}
.flex-box .col {
border: 1px solid grey;
flex: 0.33;
padding: 12px;
overflow-y: auto;
overflow-x: hide;
}
.flex-box .col:last-child {
margin-left: -6px;
}
.handle {
width: 5px;
text-align: center;
transition: all ease-in 0.1s;
z-index: 999;
overflow: visible;
}
.handle-inner{
width: 5px;
height: 100%;
position: relative;
margin-left: -10px;
}
.draggable {
background: grey;
}
Jsbin :
https://jsbin.com/nupefekuhu/edit?html,css,js,output

Related

document.addEventListener blocking highlight in textarea

I did a div that is moveable but unfortunetaly the function that let user move the div also block the highlight of the text in the text area behind.
I would like to keep the possibility to move the div and to highlight the text in textarea like I want.
Ps: I already tried to put the addEventListener on varMoveButtonNotesWindow but it's really ncomfortable to use it like that (we need to keep the cursor in the little box, and I dont want the box to be bigger it wouldn't look good).
Here's the code:
var mousePosition;
var offset = [0,0];
var isDown = false;
var varMoveButtonNotesWindow = document.getElementById('moveButtonNotesWindow');
var varNotesWindow = document.getElementById('notesWindow');
varMoveButtonNotesWindow.addEventListener('mousedown', function(e) {
isDown = true;
offset = [
varNotesWindow.offsetLeft - e.clientX,
varNotesWindow.offsetTop - e.clientY
];
}, true);
document.addEventListener('mouseup', function() {
isDown = false;
}, true);
//The bug occurs here
document.addEventListener('mousemove', function(event) {
event.preventDefault();
if (isDown) {
mousePosition = {
x : event.clientX,
y : event.clientY
};
varNotesWindow.style.left = (mousePosition.x + offset[0]) + 'px';
varNotesWindow.style.top = (mousePosition.y + offset[1]) + 'px';
}
}, true);
//so far
function closeNotesWindow() {
varNotesWindow.classList.remove('show');
}
function openNotesWindow() {
windowsModalContainer.classList.remove('show');
varNotesWindow.classList.add('show');
};
.firstTextarea {
height: 300px;
width: 300px;
}
#notesWindow {
display: block;
position: absolute;
width: 300px;
height: 275px;
top: 0px;
left: 0px;
border: 2px solid #313131;
z-index: 2;
resize: both;
overflow: auto;
}
#headerNotesWindow {
height: 35px;
background-color: black;
}
#moveButtonNotesWindow {
position: absolute;
background-color: blue;
color: white;
width: 20px;
height: 20px;
right: 5px;
z-index: 1;
top: 7.5px;
}
#closeButtonNotesWindow {
position: absolute;
background-color: red;
color: white;
width: 20px;
height: 20px;
right: 30px;
z-index: 1;
top: 7.5px;
}
#divTextareaNotesWindow {
text-align: center;
height: calc(100% - 6px - 35px);
}
#textareaNotesWindow {
resize: none;
width: calc(100% - 6px);
height: 100%;
outline: none;
}
<textarea class="firstTextarea">Pokemon is the best game of my childhood.</textarea>
<div class="divWindow" id="notesWindow">
<div id="headerNotesWindow">
<div id="moveButtonNotesWindow"></div>
<div id="closeButtonNotesWindow" onclick="closeNotesWindow()"></div>
</div>
<div id="divTextareaNotesWindow">
<textarea id="textareaNotesWindow"></textarea>
</div>
</div>
This can do like but not perfact:
RollBack selection when focus back it.
var mousePosition;
var offset = [0,0];
var isDown = false;
var varMoveButtonNotesWindow = document.getElementById('moveButtonNotesWindow');
var varNotesWindow = document.getElementById('notesWindow');
varMoveButtonNotesWindow.addEventListener('mousedown', function(e) {
isDown = true;
offset = [
varNotesWindow.offsetLeft - e.clientX,
varNotesWindow.offsetTop - e.clientY
];
}, true);
document.addEventListener('mouseup', function() {
isDown = false;
}, true);
//The bug occurs here
document.addEventListener('mousemove', function(event) {
event.preventDefault();
if (isDown) {
mousePosition = {
x : event.clientX,
y : event.clientY
};
varNotesWindow.style.left = (mousePosition.x + offset[0]) + 'px';
varNotesWindow.style.top = (mousePosition.y + offset[1]) + 'px';
}
}, true);
//so far
window.addEventListener('load',function(){
var logTextSelection = function(event) {
var tgItem = event.target;
tgItem.setAttribute("lastSelectionStart",tgItem.selectionStart);
tgItem.setAttribute("lastSelectionEnd",tgItem.selectionEnd);
}
var rollBackSelection = function(event){
var tgItem = event.target;
var lastSelectionStart = tgItem.getAttribute("lastSelectionStart");
var lastSelectionEnd = tgItem.getAttribute("lastSelectionEnd");
if((lastSelectionStart !== lastSelectionEnd)){
tgItem.focus();
tgItem.setSelectionRange(lastSelectionStart,lastSelectionEnd);
}
}
var docTextareas = document.getElementsByTagName('textarea');
for (var i = 0; i < docTextareas.length; i++) {
docTextareas[i].addEventListener('select', logTextSelection, true);
docTextareas[i].addEventListener('keyup', logTextSelection, true);
docTextareas[i].addEventListener('focus', rollBackSelection, true);
}
});
function closeNotesWindow() {
varNotesWindow.classList.remove('show');
}
function openNotesWindow() {
windowsModalContainer.classList.remove('show');
varNotesWindow.classList.add('show');
};
.firstTextarea {
height: 300px;
width: 300px;
}
#notesWindow {
display: block;
position: absolute;
width: 300px;
height: 275px;
top: 0px;
left: 0px;
border: 2px solid #313131;
z-index: 2;
resize: both;
overflow: auto;
}
#headerNotesWindow {
height: 35px;
background-color: black;
}
#moveButtonNotesWindow {
position: absolute;
background-color: blue;
color: white;
width: 20px;
height: 20px;
right: 5px;
z-index: 1;
top: 7.5px;
}
#closeButtonNotesWindow {
position: absolute;
background-color: red;
color: white;
width: 20px;
height: 20px;
right: 30px;
z-index: 1;
top: 7.5px;
}
#divTextareaNotesWindow {
text-align: center;
height: calc(100% - 6px - 35px);
}
#textareaNotesWindow {
resize: none;
width: calc(100% - 6px);
height: 100%;
outline: none;
}
<textarea class="firstTextarea">Pokemon is the best game of my childhood.</textarea>
<div class="divWindow" id="notesWindow">
<div id="headerNotesWindow">
<div id="moveButtonNotesWindow"></div>
<div id="closeButtonNotesWindow" onclick="closeNotesWindow()"></div>
</div>
<div id="divTextareaNotesWindow">
<textarea id="textareaNotesWindow"></textarea>
</div>
</div>
OK I found it, i just created a div that replace document for the addeventListener.
Ps I set the color to rgba(0, 175, 0, 0.3) just for you to see how it react and work you can obviously change it to 0.
function start() {
varNotesWindow.classList.add('show');
}
var mousePosition;
var offset = [0,0];
var isDown = false;
var varMoveButtonNotesWindow = document.getElementById('moveButtonNotesWindow');
var varNotesWindow = document.getElementById('notesWindow');
const constAlternativeDocumentForMoveButtonsWindow = document.getElementById('alternativeDocumentForMoveButtonsWindowId');
//Start Move Notes Window
varMoveButtonNotesWindow.addEventListener('mousedown', function(e) {
isDown = true;
offset = [
varNotesWindow.offsetLeft - e.clientX,
varNotesWindow.offsetTop - e.clientY
];
constAlternativeDocumentForMoveButtonsWindow.classList.add('use');
}, true);
constAlternativeDocumentForMoveButtonsWindow.addEventListener('mousemove', function(event) {
event.preventDefault();
if (isDown) {
mousePosition = {
x : event.clientX,
y : event.clientY
};
varNotesWindow.style.left = (mousePosition.x + offset[0]) + 'px';
varNotesWindow.style.top = (mousePosition.y + offset[1]) + 'px';
}
}, true);
constAlternativeDocumentForMoveButtonsWindow.addEventListener('mouseup', function() {
constAlternativeDocumentForMoveButtonsWindow.classList.remove('use');
});
document.addEventListener('mouseup', function() {
isDown = false;
}, true);
//End Move Notes Window
function closeNotesWindow() {
varNotesWindow.classList.remove('show');
}
function openNotesWindow() {
windowsModalContainer.classList.remove('show');
varNotesWindow.classList.add('show');
};
.alternativeDocumentForMoveButtonsWindowClass {
display: none;
}
.alternativeDocumentForMoveButtonsWindowClass.use {
display: block;
position: absolute;
z-index: 3;
width: 100%;
height: 100%;
left: 0;
top: 0;
background-color: rgba(0, 175, 0, 0.3);
}
#notesWindow {
display: none;
}
#notesWindow.show {
display: block;
position: absolute;
width: 300px;
height: 275px;
top: 0px;
left: 0px;
border: 2px solid #313131;
z-index: 2;
resize: both;
overflow: auto;
}
#headerNotesWindow {
height: 35px;
background-color: black;
}
#moveButtonNotesWindow {
position: absolute;
background-color: blue;
color: white;
width: 20px;
height: 20px;
right: 5px;
z-index: 1;
top: 7.5px;
}
#closeButtonNotesWindow {
position: absolute;
background-color: red;
color: white;
width: 20px;
height: 20px;
right: 30px;
z-index: 1;
top: 7.5px;
}
#divTextareaNotesWindow {
text-align: center;
height: calc(100% - 6px - 35px);
}
#textareaNotesWindow {
resize: none;
width: calc(100% - 6px);
height: 100%;
outline: none;
}
<button onclick='start()'>Let's Go</div>
<div class="alternativeDocumentForMoveButtonsWindowClass" id="alternativeDocumentForMoveButtonsWindowId"></div>
<div class="divWindow" id="notesWindow">
<div id="headerNotesWindow">
<div id="moveButtonNotesWindow"></div>
<div id="closeButtonNotesWindow" onclick="closeNotesWindow()"></div>
</div>
<div id="divTextareaNotesWindow">
<textarea id="textareaNotesWindow"></textarea>
</div>
</div>

How to achieve the same function of position:sticky using jQuery or JavaScript?

I'm having a hard time figuring out why the code below doesn't work as expected.
What I'm trying to achieve is same functionality with position:sticky whereas when the scrolled reaches the top of the #second-header then fixes its position below the #header which is also fixed, however, the height of the #header is unknown which is I believe can be calculated using the function outerHeight(true) on JQuery.
Then after reaching out to the bottom of the #second-header-container, remove the fixed position of #second-header turning it back to normal position.
Due to browser compatibility issues and other customization, I cannot simply use the position:sticky of css.
It looks like my logic is wrong, and I need help.
jQuery(document).ready(function(){
var $document = jQuery(document);
var header = jQuery('#header');
var second_header = jQuery('#second-header-container').find('#second-header');
var second_header_container = jQuery('#second-header-container');
var second_header_offset = second_header.offset().top;
var second_header_container_offset = second_header_container.offset().top;
jQuery(window).scroll(function(){
var top_margin = header.outerHeight(true);
var second_header_height = second_header.outerHeight(true);
var second_header_container_height = second_header_container.outerHeight(true);
if( jQuery(window).scrollTop() > (second_header_offset - second_header_height) && jQuery(window).scrollTop() < second_header_container_height) {
second_header.addClass('fixer');
second_header.css({position:'fixed', top:top_margin, 'z-index':'999999'});
} else {
second_header.removeClass('fixer');
second_header.css({position:'relative', top:'0px', 'z-index':'0'});
}
});
});
*{
color: #FFFFFF;
padding: 0;
margin: 0;
}
.fixer{
position: fixed;
width: 100%;
}
#header, .banner, #second-header, .contents{
padding: 5px;
}
#header{
position: fixed;
width: 100%;
height: 74px;
z-index: 99999;
background-color: #000000;
}
.banner{
padding-top: 84px;
height: 200px;
background-color: #583E5B;
}
#second-header-container{
min-height: 300px;
background-color: #775F5E;
}
#second-header{
padding-bottom: 10px;
padding-top: 10px;
background-color: #4C3D3C;
}
.contents{
min-height: 200px;
background-color: #97A36D;
}
.footer{
background-color: #80A379;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<header id="header">HEADER</header>
<div class="banner">BANNER</div>
<div id="second-header-container">
<div id="second-header">SECOND-HEADER</div>
<!--Other contents and elements...-->
</div>
<div class="contents">OTHER...</div>
<footer class="contents footer">FOOTER</footer>
To achieve this you need first check if the scroll height is near the second div header and within the height of the second div. Then add a class that make it stick below the main header. I have created a sticky class and added it while scrolling conditions are met.
Please check below code
jQuery(document).ready(function() {
var headerHeight = $('#header').outerHeight(true);
var secondHeaderContainer = $('#second-header-container');
const secondHeaderTopPos = secondHeaderContainer.offset().top;
const secondHeaderContainerHeight = $(secondHeaderContainer).height();
$(window).scroll(function() {
const scrollTop = $(this).scrollTop();
const secondContainerHeightEnd = secondHeaderContainerHeight + secondHeaderTopPos - $('#second-header').height() - headerHeight;
if (((secondHeaderTopPos - headerHeight) <= scrollTop) && (secondContainerHeightEnd >= scrollTop)) {
$('#second-header').addClass('sticky').css('top', headerHeight);
} else {
$('#second-header').removeClass('sticky');
}
});
});
* {
color: #FFFFFF;
padding: 0;
margin: 0;
}
.sticky {
position: fixed;
width: 100%;
top: 0;
left: 0;
}
.fixer {
position: fixed;
width: 100%;
}
#header,
.banner,
#second-header,
.contents {
padding: 5px;
}
#header {
position: fixed;
width: 100%;
height: 74px;
z-index: 99999;
background-color: #000000;
}
.banner {
padding-top: 84px;
height: 200px;
background-color: #583E5B;
}
#second-header-container {
min-height: 300px;
background-color: #775F5E;
}
#second-header {
padding-bottom: 10px;
padding-top: 10px;
background-color: #4C3D3C;
}
.contents {
min-height: 200px;
background-color: #97A36D;
}
.footer {
background-color: #80A379;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<header id="header">HEADER</header>
<div class="banner">BANNER</div>
<div id="second-header-container">
<div id="second-header">SECOND-HEADER</div>
<!--Other contents and elements...-->
</div>
<div class="contents">OTHER...</div>
<footer class="contents footer">FOOTER</footer>

How to make a div resizer with pure JAvaScript

I am trying to create a div resizer and due to some restrictions, I cannot use jQuery and I am forced to use pure JavaScript for that. In the current state, it works, but it breaks if the div that will have the slider does not have the position set to absolute. Is there a way to solve that issue? Thank you very much.
I am a student learning to write JavaScript/CSS/HTML code and so I am relatively new to this.
const BORDER_SIZE = 4;
const panel = document.getElementById("left_panel");
const StationaryPanel = document.getElementById("right_panel");
const parent = document.getElementById("parent");
const label1 = document.getElementById("lb1");
const label2 = document.getElementById("lb2");
const label3 = document.getElementById("lb3");
let m_pos;
function resize(e) {
const dx = m_pos - e.x;
m_pos = e.x;
lb1.innerHTML = panel.offsetWidth;
lb2.innerHTML = StationaryPanel.offsetWidth;
lb3.innerHTML = parent.offsetWidth;
//lb3.innerHTML = document.body.clientWidth;
panel.style.width = (parseInt(getComputedStyle(panel, '').width) + dx) + "px";
StationaryPanel.style.width = (parent.offsetWidth - panel.offsetWidth) + "px";
//StationaryPanel.style.width = (document.body.clientWidth - panel.offsetWidth) + "px";
}
panel.addEventListener("mousedown", function(e) {
if (e.offsetX < BORDER_SIZE) {
m_pos = e.x;
if (panel.style.width < panel.minWidth || panel.style.width > panel.maxWidth) {
return;
}
document.addEventListener("mousemove", resize, false);
}
}, false);
document.addEventListener("mouseup", function() {
document.removeEventListener("mousemove", resize, false);
}, false);
#left_panel {
position: absolute;
width: 96px;
min-width: 50px;
max-width: 500px;
padding-left: 4px;
height: 100%;
right: 0;
background-color: #f0f0ff;
}
#left_panel::before {
content: " ";
background-color: #ccc;
position: absolute;
left: 0;
width: 4px;
height: 100%;
cursor: w-resize;
}
#right_panel {
width: 1000px;
height: 100%;
background-color: #ff0000;
}
#parent {
width: 800px;
}
<body>
<div id="parent">
<div id="left_panel">
This is the left div, the one that moves
</div>
<div id="right_panel">
This is the right div, the one that stays the same
</div>
</div>
<p id="lb1"></p>
<p>This is the left panel width ^</p>
<p id="lb2"></p>
<p>This is the right panel width ^</p>
<p id="lb3"></p>
<p>This is the parent width ^</p>
</body>
Here is the simplest way you can do it using CSS if that is not an issue here no need to use JS for this feature, it is just an example but it definitely help you on your way.
#MainDiv {
display: flex;
flex-direction: row;
height: 200px;
width: 400px;
border: 1px solid red;
position: relative;
}
#leftDiv {
width: 200px;
border: 1px solid yellow;
}
#rightDiv {
border: 2px solid;
padding: 20px;
width: 300px;
/* you can make this vertical/auto to make resize both ways */
resize: horizontal;
overflow: auto;
}
<div id="MainDiv">
<div id="leftDiv">
Left Div
</div>
<div id="rightDiv">
Right Div
</div>
</div>
Here is it in Javascript:
var h = $('#handle'),
l = $('#left'),
r = $('#right'),
w = $('body').width() - 18;
var isDragging = false;
h.mousedown(function(e) {
isDragging = true;
e.preventDefault();
});
$(document).mouseup(function() {
isDragging = false;
}).mousemove(function(e) {
if (isDragging) {
l.css('width', e.pageX);
r.css('width', w - e.pageX);
}
});
#left,
#right {
border: 1px solid #aaa;
float: left;
height: 100px;
width: 48%;
}
#handle {
background: #000;
float: left;
height: 100px;
margin: 1px;
/* Slider width */
width: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="left"> Left</div>
<div id="handle"></div>
<div id="right">Right</div>

A javascript slider array issue

Having a slider with images implementation from array, cant figure out why images dont want to be shown up from array, tryed to make a path but it didnt work.I want this code to reflect this image every time a push the button: fpoimg.com/100x100.
Im trying to fix it only with clean javascript.
Here is a sandbox
var slider = {
slides: ['100x100', '100x100', '100x100', '100x100'],
frame:0,
set:function(image){
path = path || 'http://fpoimg.com/';
document.getElementById('scr').style.backgroundImage ="url ("+path+ image+")";
},
init:function() {
this.set(this.slides[this.frame]);
},
left:function() {
this.frame--;
if(frame < 0) this.frame = this.slides.length - 1;
this.set(this.slides[this.frame]);
},
right:function() {
if(this.frame == this.slides.length) this.frame = 0;
this.set(this.slides[this.frame]);
}
};
window.onload = function() {
slider.init();
setInterval(function() {
slider.right();
},5000);
};
.scr {
margin:20px auto;
width: 600px;
height: 320px;
margin-top:20px;
background-color: white;
background-size:cover;
}
button {
position: absolute;
top: 150px;
width: 25px;
height: 150px;
font-size: 30px;
text-align: center;
background:none;
border:none;
}
.left {
left:25px;
}
.right {
right:25px;
}
<body>
<button class="left" onclick="slider.left();"><</button>
<div class="scr"></div>
<button class="right" onclick="slider.right();">></button>
</body>
On Line 6 of your Javascript, you have used getElementById('scr'). You have no element with an Id or scr, you needed to use getElementsByClassName('scr')
Your new code:
var slider = {
slides: ['100x100', '100x100', '100x100', '100x100'],
frame: 0,
set: function(image) {
path = path || 'http://fpoimg.com/';
document.getElementsByClassName('scr').style.backgroundImage = "url (" + path + image + ")";
},
init: function() {
this.set(this.slides[this.frame]);
},
left: function() {
this.frame--;
if (frame < 0) this.frame = this.slides.length - 1;
this.set(this.slides[this.frame]);
},
right: function() {
if (this.frame == this.slides.length) this.frame = 0;
this.set(this.slides[this.frame]);
}
};
window.onload = function() {
slider.init();
setInterval(function() {
slider.right();
}, 5000);
};
.scr {
margin: 20px auto;
width: 600px;
height: 320px;
margin-top: 20px;
background-color: white;
background-size: cover;
}
button {
position: absolute;
top: 150px;
width: 25px;
height: 150px;
font-size: 30px;
text-align: center;
background: none;
border: none;
}
.left {
left: 25px;
}
.right {
right: 25px;
}
<body>
<button class="left" onclick="slider.left();">
</button>
<div class="scr"></div>
<button class="right" onclick="slider.right();"></button>
</body>
It seems you've got getElementById() when you meant getElementsByClassName()

Move to specific div based on button click

I was trying to move the divs (here it's question number) based on the prev and next button. So that the selected question is always visible on screen.
Here is the demo : http://jsfiddle.net/arunslb123/trxe4n3u/12/
Screen :
click and question number and click prev or next button to understand my issue.
My code :
$("#next")
.click(function () {
$(".c.current-question")
.each(function () {
var divIdx = $(this)
.attr('id');
var scrollTo = $('#' + divIdx)
.position()
.left;
$("#scrollquestion")
.animate({
'scrollLeft': scrollTo
}, 800);
});
});
$("#prev")
.click(function () {
$(".c.current-question")
.each(function () {
var divIdx = $(this)
.attr('id');
var scrollTo = $('#' + divIdx)
.position()
.left;
$("#scrollquestion")
.animate({
'scrollLeft': -scrollTo
}, 800);
});
});
Using scrollLeft is a bit tricky. I did a small redo of your use-case based on positioning and then moving it based on left of the container. The tricky part is to reliably calculate the negative position when scrolled to the extreme right. Also, need to take into account the widths and margins.
Check the below snippet:
var $wrap = $("#numWrap"), $strip = $("#strip"),
$leftArrow = $(".wrapper > .arrows").first(),
wrapWidth = $wrap.width() + $leftArrow.width(),
margin = 10;
fill(20); select($(".numberItem").first());
$strip.on("click", ".numberItem", function() { select($(this)); });
function select($elem) {
$(".numberItem").removeClass("selected");
$elem.addClass("visited").addClass("selected");
focus($elem[0]);
}
function focus(elem) {
var stripPos = $strip.position(),
numPos = $(elem).offset(),
elemWidth = $(elem).width() + margin,
numRight = numPos.left + elemWidth;
if (numRight > wrapWidth) {
$strip.css({"left": stripPos.left - elemWidth});
}
if (numPos.left < (margin + $leftArrow.width())) {
$strip.css({"left": stripPos.left + elemWidth});
}
}
$(".wrapper").on("click", "a.arrow", function() {
var stripPos = $strip.position();
if (this.id == "lft") {
$strip.css({"left": stripPos.left + (wrapWidth / 2)});
} else {
$strip.css({"left": stripPos.left - (wrapWidth / 2)});
}
});
$(".controls").on("click", "a.arrow", function() {
var $sel = $(".selected"), numPos, $sel, elemWidth;
$elem = $sel.length > 0 ? $sel.first() : $(".numberItem").first();
if (this.id == "lft") {
$sel = $elem.prev().length > 0 ? $elem.prev() : $elem;
select($sel);
} else {
$sel = $elem.next().length > 0 ? $elem.next() : $elem;
select($sel);
}
numPos = $sel.offset(); elemWidth = $sel.width() + margin;
numRight = numPos.left + elemWidth;
if (numPos.left > wrapWidth) {
$strip.css({"left": -($sel.text()) * $sel.width() });
}
if (numRight < 0) {
$strip.css({"left": +($sel.text()) * $sel.width() });
}
});
function fill(num){
for (var i = 1; i <= num; i++) {
var $d = $("<a href='#' class='numberItem'>" + i + "</a>");
$strip.append($d);
}
}
* { box-sizing: border-box; padding: 0; margin: 0; font-family: sans-serif; }
div.wrapper {
background-color: #ddd; width: 100vw; height: 64px;
clear: both; overflow: hidden; margin-top: 16px;
}
div.arrows {
float: left; width: 10%; min-width: 24px; height: 64px; line-height: 64px;
text-align: center; vertical-align: middle; overflow: hidden;
}
div.numWrap {
float: left; height: 64px; line-height: 64px;
width: 80%; vertical-align: middle;
overflow: hidden; position: relative;
}
div.strip {
position: absolute; left: 0px;
width: auto; white-space: nowrap;
transition: left 1s;
}
a.numberItem {
display: inline-block; text-align: center; margin: 0px 8px;
background-color: #fff; border-radius: 50%; width: 48px; height: 48px;
font-size: 1.2em; line-height: 48px; text-decoration: none;
}
a.numberItem.visited { background-color: #fff; color: #000; border: 2px solid #01aebc; }
a.numberItem.selected { background-color: #01aebc; color: #fff; }
div.controls { clear: both; }
div.controls > div.arrows { width: auto; margin: 0 12px; }
a, a:focus, a:active, a:link, a:visited {
display: inline-block;
text-decoration: none; font-weight: 600;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<div class="arrows">
<a id="lft" class="arrow" href="#">〈</a>
</div>
<div id="numWrap" class="numWrap">
<div id="strip" class="strip"></div>
</div>
<div class="arrows">
<a id="rgt" class="arrow" href="#">〉</a>
</div>
</div>
<div class="controls">
<div class="arrows">
<a id="lft" class="arrow" href="#">〈 Previous</a>
</div>
<div class="arrows">
<a id="rgt" class="arrow" href="#">Next 〉</a>
</div>
<div>
Explanation:
Using absolute positioning on the number container, which is nested to get 100% width.
Markup:
<div class="wrapper">
<div class="arrows"><a id="lft" class="arrow" href="#">〈</a></div>
<div id="numWrap" class="numWrap">
<div id="strip" class="strip"></div> <!-- nesting here -->
</div>
<div class="arrows"><a id="rgt" class="arrow" href="#">〉</a></div>
</div>
CSS:
div.wrapper {
background-color: #ddd; width: 100vw; height: 64px;
clear: both; overflow: hidden; margin-top: 16px;
}
div.arrows {
float: left; width: 10%; min-width: 24px; height: 64px; line-height: 64px;
text-align: center; vertical-align: middle; overflow: hidden;
}
div.numWrap {
float: left; height: 64px; line-height: 64px;
width: 80%; vertical-align: middle;
overflow: hidden; position: relative; /* relatively positioned */
}
div.strip {
position: absolute; left: 0px; /* absolutely positioned */
width: auto; white-space: nowrap;
transition: left 1s; /* instead of jquery animate */
}
With this structure, we can now use left to control the scrolling.
For partially obscured numbers, try to gently focus-in (nudge into view) a number which is partially obscured. This can be done by checking the position relative to parent and adding the width/margin to it and also accounting for width of the left arrow (it might peep thru).
Javascript:
function focus(elem) {
var stripPos = $strip.position(),
numPos = $(elem).offset(),
elemWidth = $(elem).width() + margin,
numRight = numPos.left + elemWidth;
// if it is towards right side, nudge it back inside
if (numRight > wrapWidth) {
$strip.css({"left": stripPos.left - elemWidth});
}
// if it is towards left side, nudge it back inside
if (numPos.left < (margin + $leftArrow.width())) {
$strip.css({"left": stripPos.left + elemWidth});
}
}
Once the user has scrolled the list too far and then tries to click on previous / next buttons to select a question, then we need to move the entire container upto the selected number. We can easily do this by multiplying the question number with element width and then changing the left in positive (if towards right) or in negative (if towards left).
Javascript:
// if left of element is more than the width of parent
if (numPos.left > wrapWidth) {
$strip.css({"left": -($sel.text()) * $sel.width() });
}
// if right of element is less than 0 i.e. starting position
if (numRight < 0) {
$strip.css({"left": +($sel.text()) * $sel.width() });
}
Here is a fiddle to play with: http://jsfiddle.net/abhitalks/aw166qhx/
You will need to further adapt it to your use-case, but you get the idea.

Categories