Change amount from px to percent based - javascript

I am trying to create a carousel with a sliding effect. The basic setup is I have 2 div's wrapping around the sliding content. The first div's width (the outerWrapper) is the size of all slides width together. The next div's width (the innerWrapper) is the size of 1 div.
When it's supposed to change slides, the innerWrapper get's a translation of x amount and it animates from the css transition.
I have everything working, but there's one thing I want to change. I want to change from pixel to percent.
Line 29:
innerWrapper.style.transform = 'translateX(-' + imgWidth * targetIndex + 'px)';
I tried a lot of things, but nothing worked. The only thing that worked was targetIndex * 20 + %, but that only works for 5 divs. It's not a concrete solution. How can I make the translateX percentage based?
JSFiddle
var trigger = document.getElementsByClassName('trigger'),
outerWrapper = document.createElement('div'),
innerWrapper = document.createElement('div'),
slide = document.getElementsByClassName('slide'),
parentElm = slide[0].parentNode,
imgWidth = slide[0].offsetWidth,
lastElm = trigger.length - 1,
previousSelectedIndex = 0;
innerWrapper.id = 'innerWrapper';
outerWrapper.id = 'outerWrapper';
trigger[0].className += ' selected';
innerWrapper.style.width = imgWidth * (lastElm + 1) + 'px';
while (slide.length) {
innerWrapper.appendChild(slide[0]);
}
for (var i = 0; i < trigger.length; i++) {
trigger[i].addEventListener('click', function(e) {
clickEvent(e);
})
}
function clickEvent(e) {
if (!hasClass(e.target, 'selected')) {
var targetIndex = [].slice.call(trigger).indexOf(e.target);
innerWrapper.style.transform = 'translateX(-' + imgWidth * targetIndex + 'px)';
e.target.className += ' selected';
removeClass(trigger[previousSelectedIndex], 'selected');
previousSelectedIndex = targetIndex;
}
}
outerWrapper.appendChild(innerWrapper);
parentElm.appendChild(outerWrapper);
function hasClass(element, cls) {
return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;
}
function removeClass(ele, cls) {
if (hasClass(ele, cls)) {
var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
ele.className = ele.className.replace(reg, ' ');
}
}
#outerWrapper {
float: left;
width: 270px;
height: 266px;
overflow: hidden;
}
#innerWrapper {
position: relative;
display: flex;
transition: transform 0.7s cubic-bezier(0.45, 0.05, 0.55, 0.95);
}
ul.triggers li {
float: left;
margin: 0 5px;
font: bold 16px arial;
cursor: pointer;
background-color: #ccc;
padding: 10px;
}
ul.triggers li.selected {
background-color: orange;
}
<img class="slide" width="270" src="http://i.imgur.com/XyWadkY.jpg" />
<img class="slide" width="270" src="http://i.imgur.com/OpP86hg.jpg" />
<img class="slide" width="270" src="http://i.imgur.com/oWbhwWT.jpg" />
<img class="slide" width="270" src="http://i.imgur.com/IXcqVB1.jpg" />
<img class="slide" width="270" src="http://i.imgur.com/OpP86hg.jpg" />
<ul class="triggers">
<li class="trigger">1</li>
<li class="trigger">2</li>
<li class="trigger">3</li>
<li class="trigger">4</li>
<li class="trigger">5</li>
</ul>

Try this,
innerWrapper.style.transform = 'translateX(-' + (targetIndex*(100/document.getElementsByClassName("slide").length)) + '%)';

Related

css 3d transform rotate (x + y) using mouse drag

i was recently diving into the world of css transform and wanted to rotate a div (x and y axis), i was able to do it with 2 sliders with 0 to 360 degree range but now looking forward to do it with dragging the mouse, i have made a very sloppy effort on that looking for suggestion to fix it:
jsfiddle link to test
"use strict";
let elContainer = $('#container');
let elBox = $('#box');
$(document).ready(function() {
$('.slider-rotate').on('input', function() {
sliderRotate();
});
elContainer.mousedown(function(e) {
initDragRotate(e);
});
elContainer.mousemove(function(e) {
dragRotate(e);
});
elContainer.mouseup(function(e) {
endDragRotate();
});
});
let dragging = false;
let delta = {};
function initDragRotate(e) {
dragging = true;
delta = {
x: e.pageX,
y: e.pageY,
};
}
function dragRotate(e) {
if (!dragging) {
return;
}
delta.x = e.pageX - delta.x;
delta.y = e.pageY - delta.y;
let rotateParam = '';
rotateParam += ' rotate' + 'Y' + '(' + delta.x + 'deg)';
rotateParam += ' rotate' + 'X' + '(' + delta.y + 'deg)';
elBox.css('transform', rotateParam);
}
function endDragRotate() {
if (!dragging) {
return;
}
dragging = false;
}
function sliderRotate() {
let rotateParam = '';
$('.slider-rotate').each(function() {
rotateParam += ' ' + getRotateParamString($(this));
});
elBox.css('transform', rotateParam);
}
function getRotateParamString(elClass) {
let val = elClass.val();
let rotateType = elClass.data('rotateType');
let rotateParam = 'rotate' + rotateType + '(' + val + 'deg)';
return rotateParam;
}
#container {
background: #ccc;
padding: 10vh;
display: flex;
align-items: center;
justify-content: center;
}
#box {
width: 30vh;
height: 30vh;
border: 5px solid #000;
position: relative;
transform-style: preserve-3d;
}
#box>div {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
<div id="box">
<div style="background: #f00;"></div>
<div style="background: #0f0;"></div>
</div>
</div>
<div id="control">
<br>
<label>
x
<input type="range" class="slider-rotate" data-rotate-type="X" min="0" max="360" value="0">
</label>
<br>
<label>
y
<input type="range" class="slider-rotate" data-rotate-type="Y" min="0" max="360" value="0">
</label>
</div>
also, there's 2 div on top and bottom (green and red) with transform-style preserve-3d property, hoping that it's show the other color when flipped but no luck! please suggest, thanks!
The calulation for how much to rotate is a little odd.
I believe what you need is to have the amount of rotation dependent on the amount the mouse is placed across and down the screen. To make this proportional to the screen size you need to divide it by the screen size and then multiply it by 360 to get the full range from pageX/Y being 0 to being at the right/bottom of the screen.
"use strict";
let elContainer = $('#container');
let elBox = $('#box');
$(document).ready(function() {
$('.slider-rotate').on('input', function() {
sliderRotate();
});
elContainer.mousedown(function(e) {
initDragRotate(e);
});
elContainer.mousemove(function(e) {
dragRotate(e);
});
elContainer.mouseup(function(e) {
endDragRotate();
});
});
let dragging = false;
let delta = {};
function initDragRotate(e) {
dragging = true;
delta = {
x: e.pageX,
y: e.pageY,
};
}
function dragRotate(e) {
if (!dragging) {
return;
}
// THIS IS THE CALCULATION THAT HAS CHANGED
delta.x = e.pageX / window.innerWidth * 360; //- delta.x;
delta.y = e.pageY / window.innerHeight * 360; // - delta.y;
let rotateParam = '';
rotateParam += ' rotate' + 'Y' + '(' + delta.x + 'deg)';
rotateParam += ' rotate' + 'X' + '(' + delta.y + 'deg)';
elBox.css('transform', rotateParam);
}
function endDragRotate() {
if (!dragging) {
return;
}
dragging = false;
}
function sliderRotate() {
let rotateParam = '';
$('.slider-rotate').each(function() {
rotateParam += ' ' + getRotateParamString($(this));
});
elBox.css('transform', rotateParam);
}
function getRotateParamString(elClass) {
let val = elClass.val();
let rotateType = elClass.data('rotateType');
let rotateParam = 'rotate' + rotateType + '(' + val + 'deg)';
return rotateParam;
}
#container {
background: #ccc;
padding: 10vh;
display: flex;
align-items: center;
justify-content: center;
}
#box {
width: 30vh;
height: 30vh;
border: 5px solid #000;
position: relative;
transform-style: preserve-3d;
}
#box>div {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
<div id="box">
<div style="background: #f00;"></div>
<div style="background: #0f0;"></div>
</div>
</div>
<div id="control">
<br>
<label>
x
<input type="range" class="slider-rotate" data-rotate-type="X" min="0" max="360" value="0">
</label>
<br>
<label>
y
<input type="range" class="slider-rotate" data-rotate-type="Y" min="0" max="360" value="0">
</label>
</div>

Transform orgin not being implemented

Attempting to transform an images scale (zoom) BUT maintain it inside it's parents left and top div so only trying to transform it down and to the right. Setting the transform orgin does not seem to work, what am I missing?
the following code zooms the image on each button click, but pushes the left and top out of the parent div.
$('element').click(function{
$('#element').css({'transform':'scale(' + scale + ')' });
$('#element').css({'transform-orgin':'top left'});
})
<div style "max-wdith:1080px; height: 700px; overflow-x:scroll; overflow-y:scroll">
<img id="element" src=" src="https://images.techhive.com/images/article/2017/03/castle_moat-100714623-large.jpg" " class="img-flud">
</div>
You can try the below code
var x = 400 + 'px';
var y = 300 + 'px';
$('#element').css({
'transform-origin': x + ' ' + y + ' 0px',
'-webkit-transform-origin': x + ' ' + y + ' 0px'
});
Updated answer!
const btn = document.querySelector('button');
function zoomIn(e) {
const scale = 0.1;
const img = document.querySelector('#my-image');
$('#my-image').css({transformOrigin: "top left", transform: 'scale(' + scale + ')'});
}
btn.addEventListener('click', zoomIn);
div {
width: 400px;
height: 400px;
border: 1px solid black;
overflow: hidden;
float: left;
}
div > img {
width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<img id="my-image" src="https://images.techhive.com/images/article/2017/03/castle_moat-100714623-large.jpg" />
</div>
<button>Zoom In</button>

How to flip a dynamically added image using jquery?

.html
<tbody id="item-determination" class="item-table">
</tbody>
.js
$('<td><img src="image/' + item['Group 1'].toLowerCase() + '.png"/></td>').appendTo(tr);
The image gets updated and appended to the table according to the data that comes from the service program.
On hovering over the image I want it to flip and show some text, like it happens here : https://www.ostraining.com/images/coding/jquery-flip/demo/
But as I am not using the similar structure of html, how can I get the same affect from the JQuery line that I am using?
Any kind of help would be greatly appreciated. Thanks.
$(function () {
//var $btnAdd = $('#btn-add-item');
//var $rbFlipType = $('input[name=flipType]');
var $tblItems = $('#tbl-items');
var $tbodyItems = $tblItems.children('tbody');
$(function () {
//var flipType = $rbFlipType.filter(':checked').val();
//var random = Math.random() * 9999999999999999;
var item = `<tr>
<td>
<div class="flippable-container">
<div class="flippable">
<img src="image/' + item['Group 1'].toLowerCase() + '.png" title=""/>
<h1>$('<td></td>').text(item['Group 1']).appendTo(tr)</h1>
</div>
</div>
</td>
</tr>`;
$tbodyItems.append(item);
});
});
</script>
You can do the flipping animation through CSS but you really have to restructure the HTML I guess.
$(function () {
var $btnAdd = $('#btn-add-item');
var $rbFlipType = $('input[name=flipType]');
var $tblItems = $('#tbl-items');
var $tbodyItems = $tblItems.children('tbody');
$btnAdd.click(function () {
var flipType = $rbFlipType.filter(':checked').val();
var random = Math.random() * 9999999999999999;
/* Template literal
var item = `<tr>
<td>
<div class="flippable-container">
<div class="flippable ${flipType}">
<img src="http://lorempixel.com/400/200/cats?randomQueryString=${random}" title="">
<h1>${flipType}</h1>
</div>
</div>
</td>
</tr>`;
*/
var item = '<tr>' +
'<td>' +
'<div class="flippable-container">' +
'<div class="flippable ' + flipType + '">' +
'<img src="http://lorempixel.com/400/200/cats?randomQueryString=' + random + '" title="">' +
'<h1>' + flipType + '</h1>' +
'</div>' +
'</div>' +
'</td>' +
'</tr>';
$tbodyItems.append(item);
});
});
* {
margin: 0;
padding: 0;
}
html, body {
font: normal 14px/1.8 Helvetica, Arial, sans-serif;
}
.flippable-container {
perspective: 1000px;
}
.flippable {
height: 200px;
position: relative;
transform-style: preserve-3d;
transition: 0.6s;
width: 400px;
}
.flippable img,
.flippable h1 {
backface-visibility: hidden; /* Don't show the backside of the element when rotated. */
height: 200px;
left: 0;
position: absolute;
top: 0;
width: 400px;
}
.flippable img {
z-index: 1; /* Keep the img in front. */
}
.flippable h1 {
background: #eee;
line-height: 200px;
text-align: center;
}
.flippable.vertical img {
transform: rotateX(0);
}
.flippable.vertical h1,
.flippable.vertical:hover {
transform: rotateX(180deg);
}
.flippable.horizontal img {
transform: rotateY(0);
}
.flippable.horizontal h1,
.flippable.horizontal:hover {
transform: rotateY(180deg);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<label for="rb-flip-type-horizontal">
<input id="rb-flip-type-horizontal" type="radio" value="horizontal" name="flipType">
Horizontal
</label>
<label for="rb-flip-type-vertical">
<input id="rb-flip-type-vertical" type="radio" value="vertical" name="flipType">
Vertical
</label>
<button id="btn-add-item">
Add
</button>
<table id="tbl-items">
<tbody></tbody>
</table>
</div>
Based off of David Walsh's flip.

Javascript width of span element

I create via a String some DOM-Elements and assign it via innerHTML to a div.
Now I need a flexible width of the span element (span_homebase). What I experience is that sometimes (for me it looks randomly) it returns other width than expected. I need the width of this span element because after this in the same line there is an Information Button but the width of the span could be different. So I use the width of span element as margin for the information button. Code is as follows. I searched for a async handler of innerHTML but in another post somebody said that it is not required because it is assigned instantly.
Are there any thoughts what to try? Because the information is now sometimes on the right place and sometimes not.
string = string + "<span id ='span_homebase'>" + homebaseCity + "</span>";
string = string + "<div class='section-end'></div>";
element.innerHTML = string;
var marginInfoHomebase = document.getElementById('span_homebase').offsetWidth + 20;
document.getElementById("information_button_homebase").style.margin = "5px 0 0 " + marginInfoHomebase + "px";
Now if I open the respective site for me sometimes the marginInfoHomebase sometimes returns 108 and sometimes 183 even if the same value is assigned to span element. Very strange. Any thoughts?
EDIT:
Working Example:
function createHomeSettingsView(settingsA){
var element = document.getElementById("table-settings");
var string = "";
for(var i = 0; i < settingsA.length; i++){
for(var z = 0; z < settingsA[i].length; z++){
if(i == 1){
//Notification buttons
if(z == 1){
//homebase setting
if(window.localStorage.getItem("switch_homebase") == 1){
//homebase on
var homebaseCity = settingsA[i][z] + ": " + window.localStorage.getItem("homebase_loc");
string = string + " \
<div class='row' style='height:100px;' id='settings-sec-"+ i +"-row-" + z +"'> \
<div class='text'> \
<span id='span_homebase'>" + homebaseCity + "</span> \
</div> \
<div onClick='homebaseInfoClick();' class='information_button' id='information_button_homebase'></div>\
<div id='handleAutoSwitcherHomebase'></div>\
<div id='showRadiusRangeHomebase'>Radius: 30km</div>\
<input class='sliders' id='changeRadiusRangeHomebase' type='range' min='5' max='100' step='5' oninput='handleChangeHomebase(this.value)' onchange='handleInputHomebase(this.value)' >\
</div>";
}
else{
//homebase off
string = string + " \
<div class='row' id='settings-sec-"+ i +"-row-" + z +"'> \
<div class='text'>\
<span id='span_homebase'>" + settingsA[i][z] + "</span> \
</div> \
<div onClick='homebaseInfoClick();' class='information_button' id='information_button_homebase'></div>\
<div id='handleAutoSwitcherHomebase'></div>\
</div>";
}
}
}
}
}
element.innerHTML = string;
var marginInfoHomebase = document.getElementById("span_homebase").offsetWidth + 25;
var marginText = "5px 0 0 " + marginInfoHomebase + "px";
console.log("Span: " + marginInfoHomebase);
document.getElementById("information_button_homebase").style.margin = marginText;
}
CSS:
.container .table-settings{
top: 64px;
position: absolute;
padding:0;
left: 0;
right: 0;
bottom:0;
overflow-y: scroll;
-webkit-overflow-scrolling: touch;
background-color: #ECEBF3;
}
.container .table-settings .row{
background-color: white;
padding-top: 14px;
height:50px;
border-bottom: 1px solid LightGray;
}
.container .table-settings .row .text{
margin-left: 15px;
color: black;
float: left;
}
#span_homebase{
display: inline-block;
}
To get an inline element's width use getBoundingClientRect method:
var mySpan = document.getElementById("mySpan");
var spanWidth = mySpan.getBoundingClientRect().width;
var spanHeight = mySpan.getBoundingClientRect().height;
By default a span element has no dimension because its CSS display property is inline.
If you want to give it a width, you should change that property to inline-block.
<style>
span {
display: inline-block ;
}
</style>
Now you can play with its dimensions.

Complex Jquery Selector With Variables

I am building a demo of a lotto site where a user is presented with one section full of the balls and a second section that will fill up with his/her selections.
What I am trying to do is create a jQuery function that will run when a user clicks on a ball, this function must retrieve the number of the ball that was clicked as well as the color of the ball (background-image) and then set the number and the background-image to the next available ball.
Here is a jsFiddle: http://jsfiddle.net/8kq5p6gb/1/
This is my jQuery function, it stores the number and background of the clicked ball and then tries to find the next available ball open and applies that text and background to it but it currently does not work. When I click on a ball I get this error :
Uncaught Error: Syntax error, unrecognized expression: [object Object] a:nth-child(1)
For Code :
$(document).ready(function () {
var line_counter = 1;
var number_counter = 1;
$('.draw-selection-wrapper.choice .draw-number').click(function (e) {
event.preventDefault(e);
var number = $(this).text(); ;
var background = $(this).css('background-image');
var row = $('.draw-selection-wrapper.selections div:nth-child(' + line_counter + ')');
var link = $(row + ' a:nth-child(' + number_counter + ')');
link.text(number);
link.css('background-image', background);
number_counter = number_counter + 1;
if (number_counter == 8) {
line_counter = line_counter + 1;
number_counter = 1;
}
});
});
Here is my HTML:
<div class="draw-numbers-outer-wrapper">
<div class="draw-selection-wrapper choice">
<div class="draw-number-row one">
1
2
3
4
5
6
7
</div>
<div class="draw-number-row two">
8
9
10
11
12
13
14
</div>
</div>
<div class="draw-selection-wrapper selections">
<div class="draw-number-row">
</div>
<div class="draw-number-row">
</div>
</div>
</div>
And my CSS:
.draw-selection-wrapper {
width: 50%;
float: left;
}
.draw-number-row {
height: 36px;
border: 1px solid #C6C4C5;
padding-left: 10px;
}
.line-number {
float: left;
height: 100%;
width: 12px;
}
.draw-number {
width: 9%;
float: left;
height: 100%;
line-height: 36px;
margin: 0px 2.5% 0px 2.5%;
color: #000;
text-align: center;
background-color: green;
}
.draw-selection-wrapper.selections .draw-number {
margin: 0px 2% 0px 2%;
}
.draw-number-row.one .draw-number {
background-color: red;
}
.draw-number-row.two .draw-number {
background-color: teal;
}
row is a jQuery object, not a string, and as such you end up with [Object, object] when you try to concantenate the object into a string.
You could use the context selector instead
var row = $('.draw-selection-wrapper.selections div:nth-child(' + line_counter + ')');
var link = $('a:nth-child(' + number_counter + ')', row);
FIDDLE
var link = row.find('a:nth-child(' + number_counter + ')');
Fiddle
replace this
var row = $('.draw-selection-wrapper.selections div:nth-child(' + line_counter + ')');
var link = $(row + ' a:nth-child(' + number_counter + ')');
by
var row = '.draw-selection-wrapper.selections div:nth-child(' + line_counter + ')';
var link = $(row + ' a:nth-child(' + number_counter + ')');

Categories