InsertAdjacentHTML, element saves after refresh - javascript

I am able to add the elements I want, but after I refresh they disappear. How can I get the elements to save permanently while using insertAdjacementHTML or do I need to use another method?
Sample code:
function itemAdder () {
var header = document.querySelector(".list-group");
header.insertAdjacentHTML("beforeend", '<a>Item 1</a>')
};
document.getElementById("circle-add").addEventListener("click", itemAdder)

Every time an item is added, you might save the container's current innerHTML in localStorage, and on page load, if anything exists in localStorage, populate the container with whatever's stored:
var header = document.querySelector(".list-group");
if (localStorage.headerHTML) header.innerHTML = localStorage.headerHTML;
function itemAdder () {
header.insertAdjacentHTML("beforeend", '<a>Item 1</a>')
localStorage.headerHTML = header.innerHTML;
}
document.getElementById("circle-add").addEventListener("click", itemAdder)
(hopefully you have a way to delete items as well - on deletion, use the same line localStorage.headerHTML = header.innerHTML; to save the HTML again)

Related

Inserted JS elements disappear after ajax reload

I am using a WP Plugin FacepWP and want to add reset to the dropdown.
I have used JS to create elements and add the function FWP.reset('country_2').
The problem I have is that when I click reset the page reloads (AJAX I think) and I lose the elements I added by JS
$(document).ready(function(){
function addEle() {
var newElement = document.createElement("a")
newElement.className = 'wf-reset'
newElement.onclick = function() { FWP.reset('country_2')}
newElement.textContent='Reset'
var insertReset = document.querySelector('.facetwp-facet-country_2 .fs-dropdown')
console.log(newElement);
console.log(insertReset);
insertReset.appendChild(newElement)
};
window.onload = addEle;
})
I hope for my added elements to stay on click.
I believe FacetWP uses AJAX to filter and reset but it resets my added JS elements also.
Added:
On existing archive (category, tag, shop, ) or search pages, FacetWP
will automatically attempt to add a facetwp-template CSS class around
the listing. During an ajax refresh, FacetWP will only modify content
within that container element. If your pager doesn’t change after a
FacetWP refresh, then the CSS class may need to to be manually placed
so that it surrounds both the listing and pager.
Sounds like I need to find this class and do something with it to make sure ajax reload keeps the JS I added.

Create a button which duplicate elements of an array

Hello everybody I'm new in javascript. I want to create a button which duplicate elements in an array. I try this :
%a.btn.btn-success#addd{ :href => "#", :onclick => "duplicate(this.parentNode.parentNode)" }
:javascript
document.getElementById('addd').click = duplicate;
var i = 0;
var original = document.getElementById('inf_finding.id');
function duplicate(original) {
var clone = original.cloneNode(true);
clone.id = "inf_finding.id" + ++i;
original.parentNode.appendChild(clone);
}
But I refresh it, the element that I add is not in the page anymore.Can you help me to resolve this please ?
Here are the screenshots :
First
It add properly the element
But when I refresh the page, the element disappears.
Your code only makes changes within the DOM of the current webpage. When the page is refreshed, the DOM is regenerated from the HTML sent by the server and so your changes are lost.
In order to make persistent changes, you need to save data either on the server (using AJAX) or in the browser using Local Storage, Cookies, etc.

Swapping contents in Drag and Drop

I am using drag and drop so that students can take pieces of a jumbled up image and drop them on to a grid to recompose the original image.
Both grids (jumbled up and reconstruction) allow for dropping, and everything works fine.
However, there might be cases where a student drops one object on top of another, and I want to have the code move the original object to the one recently vacated by the selected item.
I have experimented with different concepts and might be going down the wrong route but used the following for testing:
function drop(ev) {
ev.preventDefault();
var tgt = ev.dataTransfer.getData("text");
var currentContents = document.getElementById(tgt);
ev.target.appendChild(document.getElementById(tgt));
var newContents = document.getElementById(tgt);
alert("Current = " + currentContents + " - New = " + newContents);
}
The idea here was that I could simply store the element details itself, or the innerHTML into a variable, allow the drop to happen as it would normally, then assign the captured HTML to the previous div.
However, the code above only reports [object HTMLimageElement] (even though, in this case, the recipient does not contain any image data).
I tried innerHTML but simply received nothing at all.
And I haven't even begun to work out how to identify the original div that the dragged image came from.
Okay, spent some time exploring all of the values I could make sense of.
I ended up with this:
function drop(ev) {
ev.preventDefault();
var prntId = ev.target.parentNode.id;
var tgt = ev.dataTransfer.getData("text");
var tgtId = ev.target.id;
if (prntId === "targetDiv") {
ev.target.appendChild(document.getElementById(tgt));
imgPos[searchList(tgt)] = tgtId;
} else {
var thought = document.getElementById(prntId);
var orgHTML = thought.innerHTML;
var listPos = imgPos[searchList(tgt)];
thought.removeChild(thought.firstChild);
thought.appendChild(document.getElementById(tgt));
document.getElementById(listPos).innerHTML = orgHTML;
imgPos[searchList(tgtId)] = listPos;
imgPos[searchList(tgt)] = prntId;
}
}
function searchList(searchItem) {for (i = 0; i < 24; i++) {if (imgId[i] === searchItem) {return i;}}}
Not the most beautiful piece of code I have written but functional.
I identified that when the DIV was empty, the ID being returned was the DIV's ID, yet when a child was added, the ID being returned was of the image ID. I could get the HTML img tag in its entirety, so I had everything I need.
Basically, if there is no child element to the DIV, the event target.parentNode.id returns "targetDiv". I, therefore, append a child to the DIV (ID returned by the stored data in dataTransfer), and update the image list with its new position.
However, any other value is the ID of the parent DIV. I, therefore, copy the current HTML in the target DIV into a variable (orgHTML), locate the original position that the tgt image has been dragged from, place the orgHTML data in this, now vacated, DIV.
I then continue with the drop part of the process, once I have removed any children from the DIV, updating the new position of the image within the relevant list.
That is as clear as mud (I am tired and it is late), but it might help someone, one day. :)

How do I change the color of div on a page from another page

Since I'm still learning the localStorage and cookie techniques, I am trying to change the color of the div on page1.html from page2.html by using the submit button, color of the div should be changed permanently when the user clicks submit button on page2.html
This is what I got on page1:
window.onload = function() {
var anchors = document.getElementsByClassName("circleBase type1");
for(var i = 0; i < anchors.length; i++) {
anchors[i].onclick = function() {
window.open("EnterInformation.html");
}
}
}
on page2 i used localStorage for saving data permanently, with this save I need to change the color of the div on page1.
This is page2 so far:
function SaveInfo() {
localStorage.Yritys = $('#Yritys').val();
localStorage.Henkilönimi = $('#Henkilönimi').val();
localStorage.Asema_yrityksessa = $('#Asema_yrityksessa').val();
localStorage.Puhelin_Nr = $("#Puhelin_Nr").val();
localStorage.e_Mail = $('#e_Mail').val();
localStorage.Keskustelun_aihe = $('#Keskustelun_aihe').val();
What would be the solution to this? It would be nice to use localStorage instead of cookies. Thank You!
You can create a local storage
myCustomColor = '#2B2A28';
localStorage.setItem('myDataStorage', myCustomColor);
Then retrieve them
var myLoadedColor = localStorage.getItem('myDataStorage');
document.getElementById('myDiv').style.backgroundColor = myLoadedColor;
myDataStorage is the name of your created localStorage. You can use different names to create multiple localStorages if you would.
You can .getItem on the localStorage upon page load and then set the color of your div based on that localStorage data.
var x = document.getElementsByClassName("example");
var i;
for (i = 0; i < x.length; i++) {
x[i].style.backgroundColor = "red";
}
This little piece of code scans your page for all elements with the matching class and changes the background color then. Of course you can use it also for single elements:
var x = document.getElementByClassName("example");
x.style.backgroundColor = "red";
But in this case JavaScript will only change the first div it finds with a matching class.
To sum it up: There is no other convenient way than marking/tagging your elements in a way that they are unique and recognizable. Normally this is done by the name or the id. Class would also work but is seldomly used in this way.
Well, actually you could also iterate through the DOM and count the elments in order to change let's say the 15th div that appears. But what if you add additional divs a couple of days later? It's a very uncomfortable approach.
Use the localStorage and it will work using names or ids. You only have once to give every div it's id and/or name.

Saving ID for specific onclick element

I'm trying to create a JavaScript where you write a message and the time and message appears on the website. The function doing this is "renderMessage". However, it includes an image you can click to delete that message and then I want to write all the remaining ones again. Problem is that I don't know how to save some sort of ID so I know which image was clicked so I delete the correct position in the array of messages.
The code for renderMessage is:
function renderMessage(theMessage, theMessages){
var text = document.createTextNode(theMessage.getText());
var time = document.createTextNode(theMessage.getDate());
var div = document.getElementById("writeMessages");
div.appendChild(text);
div.appendChild(time);
var image = document.createElement('img');
image.src = 'img/deletePic.png';
div.appendChild(image);
div.appendChild(document.createElement('br'));
image.onclick = function(e){
theMessages.splice(); // This is where I don't know how to remove the correct one
removeAll(theMessages); // This removes all html code in the div and writes
// the array again (hopefully this time with the correct
// element removed from it)
};
}
Firstly, thumbs up for using plain js.
I would say you enclose the message, time and the image into another element. My be a ul li block. And, when you render the messages in DOM, you set the message id as id attribute of the li so it will be something like this
<ul>
<li>Message 1 - 10:21 PM <img src="remove jpg"/></li>
<li>Message 2 - 10:22 PM <img src="remove jpg"/></li>
</ul>
and your js code can be,
image.onclick = function () {
var message_id = this.parentNode.id;
// here you got the message id.
// splice your message array and render
}
Why are you re-rendering all the messages? You could simply
// splice your message array and render
var li = this.parentNode;
li.parentNode.removeChild(li);
}
you can save the id of the message inside an attribute of the element. eg <div class="your_message_container data-id="14">...</div>
Using jquery for example you can read that attribute with $(your_selector).attr("data-id"); and write it with $(your_selector).attr("data-id", "new_value");
As an alternative, also have a look at http://api.jquery.com/jquery.data/
Edit:
i made you a fiddle with pure js: http://jsfiddle.net/A64zh/2/ Note that the id of the message element must equal the data-message-id attribute of your delete image.
the advantage of using an element attribute for storing the id is that your javascript does not depend on the html structure like it does if you are using something like this.parentNode.parentNode.removeChild.... which would need to be changed if you would add more html layers in between the two

Categories

Resources