Vue js dynamically show/hide div - javascript

I have two divs:
<div class = "bigger">
</div>
<div class = "smaller">
</div>
I want to hide the bigger and show the smaller div if screen width < 710 and
vice versa. I'm able to trigger resize event by:
mounted() {
window.addEventListener("resize", this.displayWindowSize)
})
},
methods () {
displayWindowSize(event) {
if(document.documentElement.clientWidth > 710){
//hide smaller div
console.log("bigger");
}else{
//hide bigger div
console.log("smaller");
}
}
}
But I couldn't find in the internet how I can hide div in vuejs.
You guys have an idea?
Edit: I want to trigger this function to hide the div whenever screenwidth changes not only once.

It depends if you want to hide it remove it, if you want to remove you can do something like
methods () {
isBigger() {
return (document.documentElement.clientWidth > 710);
}
}
and your template
<div v-if="isBigger" class="bigger">
</div>
<div v-else class="smaller">
</div>
or
<div v-show="isBigger()" class="bigger">
</div>
<div v-show="!isBigger()" class="smaller">
</div>
if you want to decide which one to use then check this question out
What is better in vue.js 2, use v-if or v-show?

thx #top talent for answering fastly. Your solution didn't work for me but I slightly changed it:
if(document.documentElement.clientWidth > 710){
document.getElementsByClassName[0].style.display = "none";
document.getElementsByClassName("bigger")[0].style.display = "block";
}else{
document.getElementsByClassName("smaller")[0].style.display = "block";
document.getElementsByClassName("bigger")[0].style.display = "none";
}
workes perfect

This will be correct method.
methods () {
displayWindowSize(event) {
if(document.documentElement.clientWidth > 710){
document.querySeletor(".smaller").style.display = "none"
document.querySeletor(".bigger").style.display = "block"
console.log("bigger");
}else{
document.querySeletor(".smaller").style.display = "block"
document.querySeletor(".bigger").style.display = "none"
console.log("smaller);
}
}
}

Related

Hide element only if it contains specific text inside, using Java Script

I have these elements on my page:
<div id="123test"><p>test</p></div>
<div id="123test"><p>othertext</p></div>
And I am trying to remove the div if it contains "test" text inside, using Java Script, but it does not seem to work.
Here is my JS:
var container = document.getElementById('123test');
if (container.textContent=='test') {
container.style.display="none";
};
var container = document.getElementById('123test');
if (container.textContent == 'test') {
container.style.display = "none";
};
<div id="123test"><p>test</p></div>
<div id="123test"><p>othertext</p></div>
I also tried using :contains selector way, but the result was the same. The style of the container does not change at all. What do I do wrong? Is there another approach possible? This code is a simplified version of my project, but neither of these two work. I would be very gratefull if someone would help me to overcome the issue.
Make sure your HTML looks exactly like this:
<div id="123test"><p>test</p></div>
<!-- no whitespace or line breaks before or after <p>test</p> -->
and not like this
<div id="123test">
<p>test</p>
</div>
To avoid this problem, call trim() on container.textContent:
var container = document.getElementById('123test');
if (container.textContent.trim() == 'test') {
container.style.display = "none";
};
<div id="123test">
<p>test</p>
</div>
<div id="123test2">
<p>othertext</p>
</div>
And I am trying to remove the div if it contains "test" text inside, using Java Script [...]
If it is sufficient that test is contained, check for includes('test') instead:
var container = document.getElementById('123test');
if (container.textContent.includes('test')) {
container.style.display = "none";
};
<div id="123test">
<p>test123</p>
</div>
<div id="123test2">
<p>othertext</p>
</div>
Important sidenote: You cannot have more than one element with the same id.
Sidenote 2: :contains only exists in jQuery, not in CSS.
Sidenote 3 about using innerText: This had been my first approach, but for some strange reason on Safari/MacOS it won't hide the container:
var container = document.getElementById('123test');
if (container.innerText == 'test') {
container.style.display = "none";
};
console.log(container.innerText.length); // 6 (!) on Safari/MacOS
<div id="123test">
<p>test</p>
</div>
<div id="123test2">
<p>othertext</p>
</div>
Here is an example of checking an arbitrary DOM tree for text nodes that contain the string "test" and then hiding them by setting display: none;.
The function hideTestNodes accepts NodeList and primarily makes use of nodeType and textContent.
const wrapper = document.getElementById('wrapper')
const hideTestNodes = (children) => {
for (const child of children) {
if (child.nodeType === 1) {
// If the node is another Element, check its child nodes
hideTestNodes(child.childNodes)
}
// If the node is a text node and the content includes 'test'
// then hide the parent element containing the text node
if (child.nodeType === 3 && /test/i.test(child.textContent)) {
child.parentElement.style.display = 'none'
}
}
}
hideTestNodes(wrapper.childNodes)
<div id="wrapper">
<div>
<p>test</p>
</div>
<div>
<p>some other text</p>
</div>
<div>
<p>some deeply <span> nested test</span> text</p>
</div>
<div>
<p>this <span>includes</span> test.</p>
</div>
</div>
If you want to do that to only one specific div, then it's very simple:
NOTE: I added two seconds to let you see how it happens. you can remove the timer.
let test1 = document.getElementById("test1");
if (test1.innerHTML.includes("test")) {
setTimeout(() => {
test1.style.display = "none";
}, 2000);
}
<div id="container">
<div id="test1"><p>test</p></div>
<div id="test2"><p>othertext</p></div>
</div>
If you want to check all divs, it's still simple and you just need to make an array from them then use forEach loop to check all divs in that container:
let divs = document.getElementById("container").children;
[...divs].forEach(div => {
if (div.textContent.includes("test")) {
setTimeout(() => {
div.style.display = "none";
}, 2000);
}
});
<div id="container">
<div id="test1"><p>test</p></div>
<div id="test2"><p>othertext</p></div>
</div>

Close modal in vanilla js [duplicate]

I'd like to detect a click inside or outside a div area. The tricky part is that the div will contain other elements and if one of the elements inside the div is clicked, it should be considered a click inside, the same way if an element from outside the div is clicked, it should be considered an outside click.
I've been researching a lot but all I could find were examples in jquery and I need pure javascript.
Any suggestion will be appreciated.
It depends on the individual use case but it sounds like in this example there are likely to be other nested elements inside the main div e.g. more divs, lists etc. Using Node.contains would be a useful way to check whether the target element is within the div that is being checked.
window.addEventListener('click', function(e){
if (document.getElementById('clickbox').contains(e.target)){
// Clicked in box
} else{
// Clicked outside the box
}
});
An example that has a nested list inside is here.
You can check if the clicked Element is the div you want to check or not:
document.getElementById('outer-container').onclick = function(e) {
if(e.target != document.getElementById('content-area')) {
console.log('You clicked outside');
} else {
console.log('You clicked inside');
}
}
Referring to Here.
you can apply if check for that inside your click event
if(event.target.parentElement.id == 'yourID')
In Angular 6 and IONIC 3, I do same as here:
import {Component} from 'angular/core';
#Component({
selector: 'my-app',
template: `
<ion-content padding (click)="onClick($event)">
<div id="warning-container">
</div>
</ion-content>
`
})
export class AppComponent {
onClick(event) {
var target = event.target || event.srcElement || event.currentTarget;
if (document.getElementById('warning-container').contains(target)){
// Clicked in box
} else{
// Clicked outside the box
}
}
}
This working fine on web/android/ios.
It might be helpful for someone, Thanks.
Try this solution it uses pure javascript and it solves your problem. I added css just for better overview... but it is not needed.
document.getElementById('outer-div').addEventListener('click', function(){
alert('clicked outer div...');
});
document.getElementById('inner-div').addEventListener('click', function(e){
e.stopPropagation()
alert('clicked inner div...');
});
#outer-div{
width: 200px;
height: 200px;
position: relative;
background: black;
}
#inner-div{
top: 50px;
left: 50px;
width: 100px;
height: 100px;
position: absolute;
background: red;
}
<div id="outer-div">
<div id="inner-div">
</div>
</div>
I came up with a hack for this that's working well for me and that might help others.
When I pop up my dialog DIV, I simultaneously display another transparent DIV just behind it, covering the whole screen.
This invisible background DIV closes the dialog DIV onClick.
This is pretty straightforward, so I'm not going to bother with the code here. LMK in the comments if you want to see it and I'll add it in.
HTH!
closePopover () {
var windowBody = window
var popover = document.getElementById('popover-wrapper') as HTMLDivElement;
windowBody?.addEventListener('click', function(event){
if(popover === event.target) {
console.log("clicked on the div")
}
if(popover !== event.target) {
console.log("clicked outside the div")
}
})
}
}
I recently needed a simple vanilla JS solution which solves for:
Ignoring specific selectors including whether a parent contains one of these selectors
Ignoring specific DOM nodes
This solution has worked quite well in my app.
const isClickedOutsideElement = ({ clickEvent, elToCheckOutside, ignoreElems = [], ignoreSelectors = [] }) => {
const clickedEl = clickEvent.srcElement;
const didClickOnIgnoredEl = ignoreElems.filter(el => el).some(element => element.contains(clickedEl) || element.isEqualNode(clickedEl));
const didClickOnIgnoredSelector = ignoreSelectors.length ? ignoreSelectors.map(selector => clickedEl.closest(selector)).reduce((curr, accumulator) => curr && accumulator, true) : false;
if (
isDOMElement(elToCheckOutside) &&
!elToCheckOutside.contains(clickedEl) &&
!didClickOnIgnoredEl &&
!didClickOnIgnoredSelector
){
return true;
}
return false;
}
const isDOMElement = (element) => {
return element instanceof Element || element instanceof HTMLDocument;
}
In React you can use useClickOutside hook from react-cool-onclickoutside.
Demo from Github:
import { useClickOutside } from 'use-events';
const Example = () => {
const ref1 = React.useRef(null);
const ref2 = React.useRef(null);
const [isActive] = useClickOutside([ref1, ref2], event => console.log(event));
return (
<div>
<div ref={ref1} style={{ border: '1px dotted black' }}>
You are {isActive ? 'clicking' : 'not clicking'} outside of this div
</div>
<br />
<div ref={ref2} style={{ border: '1px dotted black' }}>
You are {isActive ? 'clicking' : 'not clicking'} outside of this div
</div>
</div>
);
};
Live demo

I am doing a toggle and I want to change the background color change of the div when the toggle function fired

My function is:
function onClickChange() {
let MyDiv = document.getElementById('myDIV')
if (MyDiv.style.display === 'none') {
MyDiv.style.display = ''
} else {
MyDiv.style.display = 'none'
}
}
And my div is:
<div id="myDIV"> Hello world</div>
<div id="backgroundColor" onClick={onClickChange}>I am div with image and I need a background color change toggle functionality based on "myDIV" toggle functionality</div>
Just as an information, I am using css "styled-components".Can anyone please help? Thanks in advance!
Happy coding :D
For this situation, you can use easily react state.
Example:
render method:
<div className={this.state.myClass} onClick={onClickChange}>I am div..</div>
onClickChange:
onClickChange() {
const {myClass} = this.state // read state first
if (myClass === 'red') {
this.setState({myClass: 'black'}) // set some black class name
} else {
this.setState({myClass: 'red'}) // set some red class name
}
}
When the state is changed, your render method is automatically called.
Dont use document.getElementById('myDIV') in REACT its antipattern.
Check below code, to change background color you can use style.backgroundColor for clicked div
function onClickChange(obj) {
let MyDiv = document.getElementById('myDIV');
//element.classList.toggle('mystyle');
if (MyDiv.style.display === 'none') {
MyDiv.style.display = ''
obj.style.backgroundColor="red";
} else {
MyDiv.style.display = 'none'
obj.style.backgroundColor="blue";
}
}
<div id="myDIV"> Hello world</div>
<div id="backgroundColor" onClick="onClickChange(this)">I am div with image and I need a background color change toggle functionality based on "myDIV" toggle functionality</div>

knockout.js - does not update display style of div tag

I have a div that would need to pop-up when an outside button is pressed.
div id="Screen5" class="grid-item modalBox" data-bind="style: { display: Display() }"
Display is a computed observable in the script updated when a subscriber function updates and observable.
self.Screen5Visible = ko.observable(false);
self.Display = ko.computed(function () {
if (self.Screen5Visible() == false) {
alert("here1");
return 'none';
} else {
alert("here2");
return 'block';
}
});
Screen5shouter.subscribe(function (newValue) {
alert("subscriber" + newValue);
self.Screen5Visible(newValue);
}, self, "change");
self.Hide = function() {
self.Screen5Visible(false);
};
The Screen5shouter successfully gets true when called from outside viewmodel. I get to "here2" and supposedly return 'block' with computable. However the binding does not seem to work like this.
Regular javascript would work with getElementId. Also the hide function, which is data-bound on an image in div successfully updates the Display() binding, the div does recieve a 'none' value.
Thank you for help.
So I got a working example for you using the visible binding. Hopefully this will help you achieve what you initially intended.
function Screen5 () {
this.Screen5Visible = ko.observable(false);
var self = this
this.show = function () {
self.Screen5Visible(true)
}
this.hide = function() {
self.Screen5Visible(false);
}
}
ko.applyBindings(Screen5)
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div id="Screen5" class="grid-item modalBox" data-bind="visible: Screen5Visible">
screen 5
</div>
<div id="Screen6" class="grid-item modalBox">
screen 6
</div>
<button data-bind="click: show">
Show Screen 5
</button>
<button data-bind="click: hide">
Hide Screen 5
</button>
I think your problem is with the display: Display() and more specifically the Display(). Knockout is evaluating the function on render and then it is done with it. It is no longer an observable from that point onward. I believe that it needs to be display: Display for knockout to subscribe to the Display property to have the effect that you are looking for.
From
<div id="Screen5" class="grid-item modalBox" data-bind="style: { display: Display() }"></div>
To
<div id="Screen5" class="grid-item modalBox" data-bind="style: { display: Display}"></div>

Displaying Go To Top button when page becomes scrollable

Just wondering How I can do this in Angular 2/4 : This might be easy but I just can't figure out.
Here is my code:
Let me explain it, I have a component which scrolls me to the top of the page, when I am at the bottom. But the floating div i.e, little red arrow always stays visible even when page need not scroll.
In Html:
Each button is dynamically linked to div. So div displays when button is clicked
<div *ngFor="let sampledata of SAMPLEDATA; trackBy: trackId">
<button (click)="transmitInfo(sampledata ,0)" > </button>
<div *ngFor="let data of sampledata .data; trackBy: trackId" >
<button (click)="transmitInfo(data,1)" > </button>
</div>
<!-- This keeps on going -->
</div>
<div>
<div *ngIf="renderdata === 0"> {{Object Data}}</div>
<div *ngIf="renderdata === 1">{{Object Data}}</div>
<div *ngIf="renderdata === 2">{{Object Data}}</div>
</div>
<div id="scroolUpRight">
<img src="../../../content/images/scrollup.png" width="50px" height="50px" (click)="scrollToTop()">
</div>
Let's assume when a user clicks on button 2 or 3, 2nd or 3rd div is displayed based on button clicked, this div's are a huge data. Page automatically becomes scrollable when these are activated.
In Css:
#scroolUpRight {
position: fixed;
bottom: 4%;
right: 2%;
}
#scroolUpRight :hover {
cursor: pointer;
}
In my Component I have this to take me to the top of the page:
ngOnInit() {
this.renderdata = 0;
}
transmitInfo(data, type): void {
if (type === 1) { this.sampleData = data; this.renderdata = 1; }
if (type === 2) { this.dataData = data; this. renderdata = 2; }
}
scrollToTop() {
return window.scrollTo(0, 0);
}
Now I don't know if this works but I did this:
toogleScroolButton(): void {
if (window.screenY > 300 ) {
console.log('window length is 300 +');
}
}
But this is a function. How can I make a function or component that auto detects when page becomes scrollable and display this div, hide it when not scrollable.
Expected Result : Is to make this div visible once person starts to scroll.
Previous Knowledge:
I used Javascript and Jquery before to do the same. But how do I use
angular2,4 or higher for this? Reason I need this is to animate this div when
person starts to scroll.
I do accept recommendations to optimize the above code. Please do let me know if any.. ;)
This Worked. I need to get HostListener to get windows scroll even to see if I can scroll the page.
window.scrollY gives me the scroll page size which helps me in finding out if I am scrolling my page. If scrollY reaches to certain count I can say I am scrolling down i.e, I can trigger an *ngIf to true if I am scrolling bottom else I can make it false. Code Below :)
Add
import { HostListener } from '#angular/core';
export class BlaBlaBla {
//And this did the trick
activateGoTop : boolean;
OnNgInit :: activateGoTop = false /* added Silly Reference please put this in ngOnInit() { --- }*/
#HostListener('window:scroll',[])
onWindowScroll() {
if ( window.scrollY > 100 ) {
this.activateGoTop = true;
} else {
this.activateGoTop = false;
}
}
}
in Html:
//Gets activated when screenY is scrolled for more than 100px
<div id="scroolUpRight" *ngIf="activateGoTop">
<img src="../../../content/images/scrollup.png" width="50px" height="50px" (click)="scrollToTop()">
</div>
Hope this helps someOne .. ;)
You can use a simple *ngIf binding with your method:
<div *ngIf="scrollButton()">
Top <button>up button</button>
</div>
with scrollButton() method simple as that:
public scrollButton():boolean {
return window.screenY > 300;
}
The div will only get rendered if scrollButton() method returns true, this allows you to customize your top button render conditions easily, because you only need to return a boolean from it.

Categories

Resources