Dynamic horizontal scroller - javascript

Trying to make this horizontal side scrolling side that moves to different elements depending on the button click.
https://codepen.io/mikayp-the-styleful/pen/eYYMRXp
The concerns are two things. One is the CSS. Looks like the elements arent moving based on their transform: translateX when I click the 'about' button. Am I missing something there?
The bigger problem is the JS. I believe this code is really inefficient. Is there a way I can restructure it so I don't have to make a function on each button click but instead one function that just moves the screen around to the specific sections? I've seen similar with traditional vertical sites but not horizontal.
function toAbout(){
var welcome = document.querySelector('.welcome');
var about = document.querySelector('.about');
var professional = document.querySelector('.professional');
var funStuff = document.querySelector('.fun-stuff');
var blog = document.querySelector('.blog');
var contact = document.querySelector('.contact');
about.className += " slide-zero";
professional.className += " slide-plus-100";
welcome.className += " slide-plus-200";
funStuff.className += " slide-plus-300";
blog.className += " slide-plus-400";
contact.className += " slide-plus-500";
};

Related

How to calculate equasion from text content of element?

I'm trying to write basic calculator in js (I'm learning) and so far i wrote something like this:
function Wprowadzanie(nacisnieto){
var temp = document.getElementById('kalkulator_linia_2').textContent;
temp = temp + nacisnieto;
document.getElementById('kalkulator_linia_2').innerHTML = temp;
}
function Dzialanie(nacisnieto){
var temp = document.getElementById('kalkulator_linia_2').textContent;
if(temp!="") document.getElementById('kalkulator_linia_1').innerHTML = document.getElementById('kalkulator_linia_1').textContent + ' ' + temp + ' ' + nacisnieto;
document.getElementById('kalkulator_linia_2').textContent = "";
}
function Rowna_Sie(){
var dzialanie = document.getElementById('kalkulator_linia_1').textContent + ' ' + document.getElementById('kalkulator_linia_2').textContent;
document.getElementById('kalkulator_linia_1').innerHTML = dzialanie + ' =';
var wynik = 0;
document.getElementById('kalkulator_linia_2').innerHTML = wynik;
}
Function Wprowadzanie is activated when a button (div) with number is pressed and gets the content of the button (0,1,2,3,etc..).
Example:
<div class="klawiatura_przycisk" onclick="Wprowadzanie(1)">1</div>
Same with function Dzialanie, it gets activated when button with +,-,* or / is pressed and gets content of that button (for example '+').
Example:
<div class="klawiatura_przycisk" onclick="Dzialanie('+')">+</div>
Function Rowna_Sie is activated when button with "=" is pressed.
<div class="klawiatura_przycisk" onclick="Rowna_Sie()";>=</div>
I tried to make function "Rowna_Sie()" calculate the content of var "dzialanie" and save it to var "wynik", but everything I tried didn't want to work. Could you please show me how to correctly finish that function?
You could use the eval function, which treats its argument as javascript code and tries to execute it. There are huge security concerns when you do this, but because the string is being built by buttons like that, and because this looks like it's just a project you're doing for fun, it should be fine. The code you need is this:
var wynik = eval(dzialanie);
I don't speak the language you named things in so it's a little hard to follow, and I may have made a small mistake in the snippet. The argument should be the string containing the equation the user has entered. So if they wanted to calculate 1+1, you need to do eval("1 + 1") to get the answer.

I have created a table in HTML by using JavaScript but 2 functions I have connected to two buttons stopped working

I have created a table in HTML with information in it by doing like this:
var tab = document.querySelector("table");
for (var obj of death_row) {
var row = `<tr><td>${obj.first_name}</td>
<td>${obj.last_name}</td>
<td>${obj.age_at_execution}</td>
<td>${obj.weight}</td>
<td>${obj.height}</td></tr>`;
tab.innerHTML += row;
}
I have created two buttons called "metric" and "imperial" and when the user clicks on them, the values in height and weight has to change to metric values (default table is showing imperial values). The code I have written for the metric button looks as so:
//Changes the height and weight values to metric values when clicking on "metric"-button.
document.getElementById("metric").onclick = function() {
var tab = document.querySelector("table");
for (var obj of death_row) {
var row = `<tr><td>${obj.first_name}</td>
<td>${obj.last_name}</td>
<td>${obj.age_at_execution}</td>
<td>${((obj.weight)/2.2046).toFixed(1)}</td>
<td>${(((Number(obj.height[0])*12*2.54) + (Number(obj.height[3])*2.54))/100).toFixed(2)}</td></tr>`;
tab.innerHTML += row;
}
};
//Changes the values back to imperial values when user clicks on the 'imperial' button
document.getElementById("imperial").onclick = function() {
var tab = document.querySelector("table");
for (var obj of death_row) {
var row = `<tr><td>${obj.first_name}</td>
<td>${obj.last_name}</td>
<td>${obj.age_at_execution}</td>
<td>${obj.weight}</td>
<td>${obj.height}</td></tr>`;
tab.innerHTML += row;
}
};
The code when clicking the imperial-button is the same as the first piece of code I posted above as the default values is imperial. The problem is that they wont work together. They work individually if I out-comment the others and I can't really seem to be able to identify the problem, so I was hoping one of you would be able to :) Also, when I Add these adjustments to the obj.height:
${(((Number(obj.height[0])*12*2.54) + (Number(obj.height[3])*2.54))/100).toFixed(2)}
I seem to lose a lot of data in the table, which I find very weird as I lose no data by adding the "/2.2046).toFixed(1)" adjustment to the weight object.. Maybe some of you have better luck at seeing through my mistakes:)
Thank you very much:)
The codepen helped immensely! I mentioned looking at the console output at one point. That's critically important because it's telling you what went wrong, so make sure you know how to see it. In codepen its at the bottom left as well, and there's a red exclamation mark in the JS showing that an error is present. When I hit the Metric button I see:
TypeError: obj.height is null
That's because some of your data has null for width or height instead of the value you're expecting, so it "crashes" and just stops at whatever row caused the problem. That's why some rows disappeared.
Two fixes I see:
Fix your data so that the values don't have null in them
Make the code more robust so it doesn't crash on invalid data (this is always preferable for any program).
For the second option, you can fix the code like this:
function MetricValues() {
var tab = document.querySelector("table");
tab.innerHTML = "";
for (var obj of death_row) {
var height = obj.height || "0' 0\"";
var row = `<tr><td>${obj.first_name}</td>
<td>${obj.last_name}</td>
<td>${obj.age_at_execution}</td>
<td>${((obj.weight)/2.2046).toFixed(1)}</td>
<td>${(((Number(height[0])*12*2.54) + (Number(height[3])*2.54))/100).toFixed(2)}</td></tr>`;
tab.innerHTML += row;
}
};
Using a temporary variable var height = obj.height || "0' 0\""; which defaults to 0' 0" fixes the crash.
BTW you definitely should read up on functions.

How can i append a child to a div that has a random number as an id?

READ THE EDIT AT THE BOTTOM! :)
I am making a little website where the user can fill in multiple text boxes, and when they come back later, their text boxes come back. (Pretty much a terrible helpdesk system using localstorage).
I have three fields the user can fill out, then when the fields are submitted they should appear below, in a div. Currently i am only able to get the first field to be shown, as i append it to a static div, but i want to append the rest of the fields to the first one. This wouldnt be too hard, but i cant seem to append a child to a div that doesnt have a set ID (without somehow hardcoding it).
I have tried things like
divAId + i.appendChild(divB)
And
var divAIdNumber = divAId + i;
divAIdNumber.appendChild(divB);
, but nothing seems to work.
Here is the code in question:
gradStorages = JSON.parse(localStorage.getItem('gradStorages'));
var iFeil = 0;
function feilDivCreate(){
const divF = document.createElement("div");
divF.className = "feilDiv";
divF.id = "feilDivId" + iFeil;
listIdIncrement();
divF.appendChild(document.createTextNode(set1));
textContainer2.appendChild(divF);
iFeil += 1;
}
var iOffer = 0;
var feilIdNumber = "feilId";
function offerDivCreate(){
const divO = document.createElement("div");
divO.className = "offerDiv";
divO.id = "offerDivId" + iOffer;
listIdIncrement();
divO.appendChild(document.createTextNode(set1));
feilIdNumber + iOffer.appendChild(divO);
iOffer += 1;
console.log(feilIdNumber + "TATATATAT");
}
var set1 = "set1 Not Defined";
var set2 = "set2 Not Defined";
var set3 = "set3 Not Defined";
function extract(){
for(let i = 0; i < feilStorages.length; i++){
set1 = feilStorages[i];
set2 = offerStorages[i];
set3 = gradStorages[i];
feilDivCreate();
offerDivCreate();
gradDivCreate(); // same as offerDiv
}
}
(can add more, or make a jsfiddle if needed.)
I need a way to append offerDiv to feilDiv, but its not so simple because feilDiv's id is feilDivId + i where i goes up by one for each new feildiv added.
Any tips for how i can achieve this?
EDIT: Here is a simplified version, showing all the code necessary to understand what im trying to do. https://codepen.io/kossi1337/pen/xxKPRvv
Might be easier to just make a new question with all the new code, but im not too sure if that allowed.. Let me know if i have to change anything about my question :)
In this code:
var divAIdNumber = divAId + i;
divAIdNumber.appendChild(divB);
It seems like you are trying to append an element to the Integer value you just created by adding i to some number. You need to grab the parent node, either via document.querySelector or using jQuery, then append to the parent. The browser has no idea what to do when you try to append markup to a number. It expects a DOM location that it will be appended to.
It should be like this:
var divAIdNumber = divAId + i;
var html = "<div class='" + divAIdNumber + "'> Content here </div>";
var element = document.querySelector(".my-element");
element.appendChild(html);

Adding component to container doesn't work

I could hardly found an easier example but for some unknown reason i have problems with this few lines of code. I dynamically create buttons and add them to my container to the end.
I don't know why but only the first button is added. Please help
Code:
var buttonCount = this.getFoldersContainer().query('button').length;
var button = Ext.create('Ext.button.Button');
button.id = 'folderButton' + record.get('id');
button.setText(record.get('name') + " >>");
console.debug('count');
console.debug(buttonCount);
this.getFoldersContainer().insert(buttonCount,button);
I created a new blank project with only this functionality and it works fine. I don't have a clue what could be causing this in my existing project.
First you should be sure that all buttons get a application wide unique id!
Next is that the id should be present at construction time of the button (in your case it will not be critical but I recommend it). It makes no sense when you are saying that add() would insert at the beginning, because it always insert at the end!
// ....getFoldersContainer().query('button').length; // count all the items!!
// you may do a check if the id is unique while debugging
if(Ext.getCmp('folderButton' + record.get('id')) != null)
console.error('Id duplicated! >> ','folderButton' + record.get('id'))
var ct = this.getFoldersContainer(),
itemCount = ct.items.getCount(),
button = Ext.create('Ext.button.Button', {text:record.get('name') + " >>",id:'folderButton' + record.get('id')});
ct.insert(itemCount > 0 ? --itemCount : itemCount ,button);
// if you just want to insert at the end you will be fine with
// ct.add(button);

JavaScript drag and drop issue

Ok I have created a JavaScript page where the user can add text, they can set the colour, bold italics, as well as size and font. Size and drop options are selected through drop down boxes.
It looks a bit messy atm, as I am not worried about the looks, just the functionality.
When they add an element which appears in the widget, they can drag the element into position onto an image I have created which is displayed on the screen. Whenever the user is happy with the position of the text, they click save which generates the coordinates and updates the table X and Y coordinates field, At this point, a new row is generated and they can repeat the process of adding a new element. Whenever they are happy, they click save and it will send to a database to store it to be retrieved later.
My problem is everytime I add a new text field, it pushes the element down by a certain amount.
I rectified this by adding a decrementing variable which takes the elementCount (which autoincrements every time they add a new label element) and multiply it by a set amount to decrement by
decr -= (elementCount* 16);
This works fine for the medium text size, however when you start adding different text sizes and font combinations, it will change how much the element gets pushed down so it gets worse and worse every other element you add.
The new element is added like this
elementCount++;
var Text = textArray[textArray.length-1];
var Font = fontArray[fontArray.length-1];
var Color = colorArray[colorArray.length-1];
var Bold = boldArray[boldArray.length-1];
var Size = sizeArray[sizeArray.length-1];
var Italics = italicsArray[italicsArray.length-1];
var X = xCordArray[xCordArray.length-1];
var Y = yCordArray[yCordArray.length-1];
var newdiv = document.createElement('div');
newdiv.innerHTML = "<span><font color='" + Color + "' size = '" + Size + "' face='" + Font + "'><label class = 'drag2' id = 'text" + firstCount + "'> " + Text + "</label></font></span>";
document.getElementById(divName).appendChild(newdiv);
var decr= 32;
decr-= (elementCount* 16);
Y = parseInt(Y) + test;
X = parseInt(X) + 24;
document.getElementById("text" + elementCount).style.left = X + "px";
document.getElementById("text" + elementCount).style.top = Y + "px";
The drag and drop JavaScript code was based on this tutorial
http://luke.breuer.com/tutorial/javascript-drag-and-drop-tutorial.aspx
Is there any way to make it so when you dynamically add a new element , it doesn't automatically push it down the screen by a bit each new element you add. I have tried soo many different options to fix this over the past few days and have had no luck.
Thanks in advance for any help
Edit CSS for the text element
.text1{
position: relative;
left: 0px;
top: 0px;
}
I changed to absolute positioning and placed it inside a relative positioned container and works perfectly now!!

Categories