JavaScript drag and drop issue - javascript

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!!

Related

Dynamic horizontal scroller

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";
};

Increment a font size onclick event

In the new JS, I would like to understand how to make a simple increase of a font size of a text.
My goal is to onclick the text and sees increasing.
I tried something like that without success:
function increaseFontSize(objId) {
obj = document.getElementById(objId);
//get current font size of obj
currentSize = parseFloat(obj.style.fontSize); //parseFloat gives you just the numerical value, i.e. strips the 'em' bit away
obj.style.fontSize = (currentSize + .1) + "em";
}
I would like to see a demo with the new JS like the querySelector or else to solve this simple issue to allow me to learn the correct way.
The style property of an element only returns style information that has been set on the style attribute in the HTML. If the style has been set via a class or through JavaScript, you will get undefined. Instead, use getComputedStyle(), which will return the current style information, regardless of how it was set.
Also, you probably don't want to increase the font size with:
currentSize + .1 + "em"
Since em is a unit that is relative to the size of the parent element. If say, an element has parent element with a font size of 16px (the default size of normal text in most browsers) and you strip off the px and then add .1em to it, you'll have a new size of 16.1em, which means 16.1 times the parent element size (16 x 16.1 = 257.6px). If you really want to use em, you should just make it 1.1 for a slight size increase, otherwise stick with px and just bump it up by 1 (shown below).
// Instead of the function only being able to work when an element
// id is passed to it, have the function work as long as an element
// reference itself is passed to it. This is more flexible, since
// not all elements will have an id.
function increaseFontSize(element) {
console.clear();
currentSize = parseFloat(getComputedStyle(element).fontSize);
console.log("Original size of: " + element.nodeName + ": " + currentSize);
element.style.fontSize = ++currentSize + "px"; // Bump up the font size by 1 and concatenate "px" to the result
console.log("New size of: " + element.nodeName + ": " + getComputedStyle(element).fontSize);
}
// Set a click event on the entire document
document.addEventListener("click", function(event){
// Run the callback and pass a reference to the actual element that was clicked
increaseFontSize(event.target);
});
<p>A long time ago</p>
<div>In a galaxy far far away</div>
<h1><div>STAR WARS</div></h1>
Get the font-size of your element (with getComputedStyle function), increase it, then assign it to the element again:
document.getElementById('myText').addEventListener("click", function () {
let fontSize = parseInt(window.getComputedStyle(this, null).getPropertyValue('font-size'));
fontSize++;
this.style.fontSize = fontSize + 'px';
});
<div id="myText">My text</div>
You want to do something like the following.
const p = document.querySelector('p');
p.addEventListener("click", updateFontSize);
function updateFontSize() {
const style = window.getComputedStyle(p, null).getPropertyValue('font-size');
const fontSize = parseFloat(style);
p.style.fontSize = (fontSize + 10) + 'px';
}
<p>Test</p>
Here is a code-sandbox demo. We are getting fontSize from computed styles and then incrementing.
https://codesandbox.io/s/pedantic-platform-4zndi

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);

Variables within function is null

I have the following function:
function slideDown() {
//get the element to slide
sliding = document.getElementById('slideDiv1');
//add 1px to the height each time
sliding.style.height = parseInt(sliding.style.height)+1+'px';
t = setTimeout(slideDown,30);
if (sliding.style.height == "401px") {
clearTimeout(t);
}
}
which is called within this function:
function addDiv(nextImageSlide) {
//finds the src attribute of the image nested in the Li
elemChild = nextImageSlide.firstChild;
imageSrc = elemChild.getAttribute('src');
//loops and creates six divs which will be the slices. adds background property etc
for (i = 0, j = 0, k = 1; i< = 19; i++, j++, k++) {
var newDiv = document.createElement('div');
newDiv.setAttribute('class', 'new-div');
newDiv.id='slideDiv' + k;
newDiv.style.height = '1px';
newDiv.style.background = 'url(' + imageSrc +') scroll no-repeat - '+39.5 * j + 'px 0';
var a = document.getElementById('content');
a.appendChild(newDiv);
}
slideDown();
}
Which is called within another function that defines nextImageSlide. It later removes all the divs that it just made.
The idea is for an image gallery. When the user hits the next button, I want slices of the next image to slide down to show the next image. Those slices are then taken away and the new image revealed.
I would like something like this: http://workshop.rs/projects/jqfancytransitions/.
It's for an assignment so we have to write all the code ourself and this is the best way I can think to replicate it. The only problem is that I keep getting an error:
'sliding is null. sliding.style.height = parseInt(sliding.style.height)+1+'px';'
No matter what I do I can't get rid of it. The thing is if I define sliding as a totally different id, (for example I made a random little div outside of everything), it working.
This error shows when I try to access the divs, it just made that it throws a hissy fit.
Anyone see any errors in my code?
Hopefully this is just a typo while pasting into the site here, but:
car a = document.getElementById('content');
^---syntax error, which'll kill your entire script - var?

Undo function not firing after keyup on textual input

I have a simple script showing the character count for a text input element or a textarea element.
$("input[type=text],textarea").keyup(function(){
var currentLength = ($(this).val().length);
var maximum = 100;
var spanLimit = $("span[name=Limit]");
spanLimit.html("("+ currentLength + " of " + maximum + ")");
});
While the script performs its function, I noticed that the user loses the ability to undo his/her typing with either Ctrl+Z or the right click menu option. If I comment out the following line, the undo function is not lost:
spanLimit.html("("+ currentLength + " of " + maximum + ")");
Is there any way to not lose the undo stack after performing DOM manipulation?
P.S. This behavior is visible when using IE8
You forgot a quote in var spanLimit = $("span[name=Limit]);.
It should be var spanLimit = $("span[name=Limit]");

Categories