js reverse remove, keep element to its DOM location - javascript

when we call element.remove(), element is removed from DOM since and element.isConnected will return false. is there a function that reverse remove method and put the element back into location?
let's say I have three elements: html_area, css_area and js_area. their display are managed individually by html_hider, js_hider, css_hider. when hider is clicked, I need to remove the area from DOM, also modifies container dimension. here's the thing, I want to keep these in order:
html
css
js
when they hide and show (appended or removed) form DOM, I want their sequence to be maintained. I manually coded it as:
html_area.connect = () => container.prepend(html_area);
css_area.connect = () => {
if(!html_area.isConnected){
container.prepend(css_area);
}else if(!js_area.isConnected){
container.append(css_area);
}else{
container.insertBefore(css_area, js_area);
}
}
js_area.connect = () => container.append(js_area);
html_hider.onclick = () => {
if(html_area.isConnected){
html_hider.classList.add('hide');
html_area.remove();
}else{
html_hider.classList.remove('hide');
html_area.connect();
}
aMode();
}
css_hider.onclick = () => {
if(css_area.isConnected){
css_hider.classList.add('hide');
css_area.remove();
}else{
css_hider.classList.remove('hide');
css_area.connect();
}
aMode();
}
js_hider.onclick = () => {
if(js_area.isConnected){
js_hider.classList.add('hide');
js_area.remove();
}else{
js_hider.classList.remove('hide');
js_area.connect();
}
aMode();
}
not robust and will be extremely complicated when elements and hiders pair more than 3. is there a way to reverse the remove method and put the element back in its original location?

Related

ReactJS - Print specific elements in the DOM

I am using ReactJS on an App and currently need to be able to print some elements from the page on user's request (click on a button).
I chose to use the CSS media-query type print (#media print) to be able to check if an element should be printed, based on a selector that could be from a class or attribute on an Element. The strategy would be to hide everything but those "printable" elements with a stylesheet looking like:
#media print {
*:not([data-print]) {
display: none;
}
}
However, for this to work I need to also add the chosen print selector (here the attribute data-print) on every parent element each printable element has.
To do that here's what I've tried so far:
export default function PrintButton() {
useEffect(() => {
const handleBeforePrint = () => {
printNodeSelectors.forEach((selector) => {
const printableElement = document.querySelector(selector);
if (printableElement != null) {
let element = printableElement;
while (element.parentElement) {
element.setAttribute("data-print", "");
element = element.parentElement;
}
element.setAttribute("data-print", "");
}
});
};
const handleAfterPrint = () => {
printNodeSelectors.forEach((selector) => {
const printableElement = document.querySelector(selector);
if (printableElement != null) {
let element = printableElement;
while (element.parentElement) {
element.removeAttribute("data-print");
element = element.parentElement;
}
element.removeAttribute("data-print");
}
});
};
window.addEventListener("beforeprint", handleBeforePrint);
window.addEventListener("afterprint", handleAfterPrint);
return () => {
window.removeEventListener("beforeprint", handleBeforePrint);
window.removeEventListener("afterprint", handleAfterPrint);
};
}, []);
return <button onClick={() => window.print()}>Print</button>;
}
With printNodeSelectors being a const Array of string selectors.
Unfortunately it seems that React ditch out all my dirty DOM modification right after I do them 😭
I'd like to find a way to achieve this without having to manually put everywhere in the app who should be printable, while working on a React App, would someone knows how to do that? 🙏🏼
Just CSS should be enough to hide all Elements which do not have the data-print attribute AND which do not have such Element in their descendants.
Use the :has CSS pseudo-class (in combination with :not one) to express that 2nd condition (selector on descendants):
#media print {
*:not([data-print]):not(:has([data-print])) {
display: none;
}
}
Caution: ancestors of Elements with data-print attribute would not match, hence their text nodes (not wrapped by a tag) would not be hidden when printing:
<div>
<span>should not print</span>
<span data-print>but this should</span>
Caution: text node without tag may be printed...
</div>
Demo: https://jsfiddle.net/6x34ad50/1/ (you can launch the print preview browser feature to see the effect, or rely on the coloring)
Similar but just coloring to directly see the effect:
*:not([data-print]):not(:has([data-print])) {
color: red;
}
<div>
<span>should not print (be colored in red)</span>
<span data-print>but this should</span>
Caution: text node without tag may be printed...
</div>
After some thoughts, tries and errors it appears that even though I managed to put the attribute selector on the parents I completely missed the children of the elements I wanted to print! (React wasn't at all removing the attributes from a mysterious render cycle in the end)
Here's a now functioning Component:
export default function PrintButton() {
useEffect(() => {
const handleBeforePrint = () => {
printNodeSelectors.forEach((selector) => {
const printableElement = document.querySelector(selector);
if (printableElement != null) {
const elements: Element[] = [];
// we need to give all parents and children a data-print attribute for them to be displayed on print
const addParents = (element: Element) => {
if (element.parentElement) {
elements.push(element.parentElement);
addParents(element.parentElement);
}
};
addParents(printableElement);
const addChildrens = (element: Element) => {
elements.push(element);
Array.from(element.children).forEach(addChildrens);
};
addChildrens(printableElement);
elements.forEach((element) => element.setAttribute("data-print", ""));
}
});
};
const handleAfterPrint = () => {
document.querySelectorAll("[data-print]").forEach((element) => element.removeAttribute("data-print"));
};
window.addEventListener("beforeprint", handleBeforePrint);
window.addEventListener("afterprint", handleAfterPrint);
return () => {
window.removeEventListener("beforeprint", handleBeforePrint);
window.removeEventListener("afterprint", handleAfterPrint);
};
}, []);
return <button onClick={() => window.print()}>Print</button>;
}
I usually don't like messing with the DOM while using React but here it allows me to keep everything in the component without having to modify anything else around (though I'd agree that those printNodeSelectors need to be chosen from outside and aren't dynamic at the moment)

Changing a HTML element dynamically

I have a side drawer where I'm showing the current cart products selected by the user. Initially, I have a <p> tag saying the cart is empty. However, I want to remove it if the cart has items inside. I'm using an OOP approach to design this page. See below the class I'm working with.
I tried to use an if statement to condition the <p> tag but this seems the wrong approach. Anyone has a better way to do this. See screenshot of the cart in the UI and code below:
class SideCartDrawer {
cartProducts = [];
constructor() {
this.productInCartEl = document.getElementById('item-cart-template');
}
addToCart(product) {
const updatedProducts = [...this.cartProducts];
updatedProducts.push(product);
this.cartProducts = updatedProducts;
this.renderCart();
}
renderCart() {
const cartListHook = document.getElementById('cart-items-list');
let cartEl = null;
if (this.cartProducts.length === 0) {
cartEl = '<h2>You Cart is Empty</h2>';
} else {
const productInCartElTemplate = document.importNode(
this.productInCartEl.content,
true
);
cartEl = productInCartElTemplate.querySelector('.cart-item');
for (let productInCart of this.cartProducts) {
cartEl.querySelector('h3').textContent = productInCart.productName;
cartEl.querySelector('p').textContent = `£ ${productInCart.price}`;
cartEl.querySelector('span').textContent = 1;
}
}
cartListHook.append(cartEl);
}
}
By the way, the <p> should reappear if the cart is back to empty :) !
With how your code is setup, you would want to reset the list on each render. You would do this by totally clearing out #cart-items-list. Here is a deletion method from this question
while (cartListHook.firstChild) {
cartListHook.removeChild(cartListHook.lastChild);
}
But you could use any method to delete the children of an HTML Node. To reiterate, you would put this right after getting the element by its id.
P.S. You probably want to put more code into your for loop, because it seems like it will only create cart-item element even if there are multiple items in this.cartProducts.

How to add an event listener to dynamically generated content using Renderer2?

I am trying to add a click event listener to a div that is dynamically generated after page load but I can't seem to get the event to register. I am following the instructions found in this answer however, it is not working for me.
In my ngOnInit() I have a combineLatest():
combineLatest([this.params$, this.user$]).subscribe(([params, user]: [Params, User]) => {
this.artistId = parseInt(params['artist']);
this.user = user;
if (this.artistId) {
this.artistProfileGQL.watch({
id: this.artistId
}).valueChanges.subscribe((response: ApolloQueryResult<ArtistProfileQuery>) => {
this.artist = response.data.artist;
this.initElements(); // WHERE I CALL TO INITIALIZE DYNAMIC DOM ELEMENTS
});
})
In this block, I call initElements() which is where I create certain DOM elements. I've included most of them below. Essentially, I have a header element, and inside this header element, I create a followBtn, that looks like this (i removed the title, followers, elements etc from the code for brevity). I added comments in caps for the most relevant lines:
initElements() {
const parentElement = this.el.nativeElement;
this.header = parentElement.querySelector('ion-header');
// Create image overlay
this.imageOverlay = this.renderer.createElement('div');
this.renderer.addClass(this.imageOverlay, 'image-overlay');
this.colorOverlay = this.renderer.createElement('div');
this.renderer.addClass(this.colorOverlay, 'color-overlay');
this.colorOverlay.appendChild(this.imageOverlay);
this.header.appendChild(this.colorOverlay);
var artistHeader = this.renderer.createElement('div');
this.renderer.addClass(artistHeader, 'artist-header');
// HERES WHERE I CREATE MY BUTTON ELEMENT
this.followBtn = this.renderer.createElement('div');
this.renderer.addClass(this.followBtn, "follow-btn");
var followText = this.renderer.createText('FOLLOW');
this.renderer.appendChild(this.followBtn, followText);
this.renderer.appendChild(artistHeader, this.followBtn);
this.renderer.appendChild(this.imageOverlay, artistHeader);
// HERES WHERE I CREATE MY LISTENER
this.followButtonListener = this.renderer.listen(this.followBtn, 'click', (event) => {
console.log(event);
});
}
However, when I click on the element, I don't get anything printed to my console. If I change the target of the listener to a DOM element, the click listener works. What am I doing wrong?

How to reset an elements class to it's initial value

How can I reset an elements 'class' attribute to it's initial value?
I am building a tooltip popup which starts with class="ttPopup". This is then set to the appropriate orientation by adding classes such as class="ttPopup top left".
Problem is when the Popup windows closes, how do I reset the class to it's original value ready for the next time?
There are several ways you could do it:
store in a custom attribute
store in a javascript array
store in localStorage
etc.
Not completely sure if I am correct to use a custom property on the element or not but here is the solution I have used at the moment:
eTooltip.addEventListener("mouseenter", function (oEvent) { ttOpen(oEvent); } );
eTooltip.addEventListener("mouseleave", function (oEvent) { ttClose(oEvent); } );
function ttOpen(oEvent) {
var thisPopup = oEvent.target.getElementsByClassName("ttPopup")[0];
thisPopup.origClassName = thisPopup.className;
}
function ttClose(oEvent) {
var thisPopup = oEvent.target.getElementsByClassName("ttPopup")[0];
if (thisPopup.origClassName) { thisPopup.className = thisPopup.origClassName; thisPopup.origClassName = null; }
console.log(thisPopup.className)
}
Thanks for your help.

jquery and multiple element hover check

I have 3 boxes and once user hovers any, if changes the content of the big main div from default to the related div via featVals hash table
At the if ($('#estate-feature, #carrier-feature, #cleaning-feature').is(':hover')) { part of my code, I want to check if any of these 3 div boxes are currently hovered, if not display the default content (defaultFeat variable).
However I am getting Uncaught Syntax error, unrecognized expression: hover error from Google Chrome Javascript Console.
How can I fix it ?
Regards
$('#estate-feature, #carrier-feature, #cleaning-feature').hover(function () {
var currentFeatCont = featVals[$(this).attr('id')];
headlineContent.html(currentFeatCont);
}, function () {
headlineContent.delay(600)
.queue(function (n) {
if ($('#estate-feature, #carrier-feature, #cleaning-feature').not(':hover')) {
$(this).html(defaultFeat);
}
n();
})
});
:hover isn't an attribute of the element. Also, you are binding to the hover out there so you know that you have left the hover and can restore the default content. If you want the hover-triggered content to remain for a period after the point has left the trigger element then you'll either need to assume that you aren't going to roll over another trigger or implement a shared flag variable that indicates if the default text restore should be halted. e.g.
var isHovered = false;
$('#estate-feature, #carrier-feature, #cleaning-feature').hover(
function() {
var currentFeatCont = featVals[$(this).attr('id')];
headlineContent.html(currentFeatCont);
isHovered = true;
},
function() {
isHovered = false;
headlineContent.delay(600)
.queue(function(n) {
if (!isHovered) {
$(this).html(defaultFeat);
}
n();
})
}
);

Categories