Is there a way to make a css property reactive with vuejs #scroll? - css

I'm making a vuejs component in my project, and i need to create a zoom with scroll, in a div (like googlemaps).
<div #scroll="scroll">
<Plotly :data="info" :layout="layout" :display-mode-bar="false"></Plotly>
</div>
<style>
div {
transform: scale(property1);
}
<\style>
<script>
export default {
methods: {
scroll(event) {
},
},
created() {
window.addEventListener('scroll', this.scroll);
},
destroyed() {
window.removeEventListener('scroll', this.scroll);
}
}
</script>
How can i make a method that make the "property1" reactive? Or there is another way to zoom with scroll only the div?

you can bind a dynamic style object to your div which includes the transform property with a dynamic value (see docs for deeper explanation):
<div #scroll="scroll" :style="{ transform : `scale(${property1})`}">
<Plotly :data="info" :layout="layout" :display-mode-bar="false"></Plotly>
</div>
new Vue({
...
data() {
return {
property1: defaultValue
}
},
methods : {
scroll(e){
// e is the event emitted from the scroll listener
this.property1 = someValue
}
}
})
You can also add some modifiers in the template as shown in the documentation to reduce the method code (here we could be preventing the page from scrolling whenever the user will be scrolling while hovering this specific element):
<div #scroll.self.stop="scroll" :style="{ transform : `scale(${property1})`}">
<Plotly :data="info" :layout="layout" :display-mode-bar="false"></Plotly>
</div>

Related

Vuejs apply loop in css to put hover

In VueJS, I have elements that have hover property in my object.
So, I want to put a foreach in style, but it is not possible.
I want to do that kind of thing :
<style>
#foreach (element in elements) {
if (element.has_backgroundhover) {
'#'+element.id:hover {
background : element.background_hover;
}
}
}
</style>
Notice that each element has a background color different (it is stored in his oibject property)
Thank you
The #mouseenter and #mouseleave event listeners would allow for css classes to be applied to each element.
For example, toggle a .hovered class that has the background color defined.
Something like this?
The HTML:
<div id="app">
<div
v-for="element of elements"
#mouseenter="element.hover=true"
#mouseleave="element.hover=false"
:style="{
background: element.hover? element.background_hover : element.background
}"
>{{element.name}}</div>
</div>
And the JS:
new Vue({
el: "#app",
data: {
elements:[
{
name:"element1",
background:"#f8f",
background_hover:"#a4a",
hover:false
},
{
name:"element2",
background:"#ff8",
background_hover:"#aa4",
hover:false
},
]
},
})
This is not using the CSS, rather using events as suggested by #DigitalDrifter. I think the point is that reactive css is not a good idea, and not supported in vue. Instead you need to have the HTML element properties dependent on your vue data object. A fiddle for this is: https://jsfiddle.net/edzaokum/

Responsive Props in Vue Component

I have a prop called src in a Vue Component that binds to a :style like this:
<template>
<section :class="color" class="hero" :style="{ backgroundImage: src && 'url(' + src + ')' }">
<slot></slot>
</section>
</template>
<script>
export default {
props: ['src', 'color']
}
</script>
What I would like to do is to create a list of responsive props that get used depending on the device or screen size of the site visitor.
For instance, I imagine a list of props like src-sm, src-md, src-lg, etc. The user would enter different image urls for different device sizes and the style attr would use the appropriate url depending on the screen/size.
Is this possible in VueJS. If so, any idea how?
Thanks.
Unfortuently what you are trying to do is not trivial. This is because inline style tags can not accept media queries.
The spec declares:
The value of the style attribute must match the syntax of the contents of a CSS declaration block
Solution 1:
This solution is the simplest, perhaps not entirely what you are looking for.
It works by including img elements, and showing an hiding them via CSS.
<template>
<div>
<img class="image--sm" :src="src.sm" />
<img class="image--md" :src="src.md" />
<img class="image--lg" :src="src.lg" />
</div>
</template>
<script>
export default {
props: {
src: Object
}
}
</script>
<style>
.image--md,
.image--lg {
display: none;
}
#media (min-width: 400px) {
.image--sm {
display: none;
}
.image--md {
display: block;
}
}
#media (min-width: 600px) {
.image--md {
display: none;
}
.image--lg {
display: block;
}
}
</style>
Example: https://jsfiddle.net/h3c5og08/1/
Solution 2:
Image tags may not be the desired effect you are trying to achieve. This solution creates a style tag in the head and injecting the css content to change the background images.
You can not have style tags in Vue template. It will throw an error like:
Templates should only be responsible for mapping the state to the UI. Avoid placing tags with side-effects in your templates, such as , as they will not be parsed.
As the error describes vue is designed the map state the UI. Using style tags in the template is prohibited because you can cause leaks to the outer world.
Although you can not declaratively styles in a template, we can use a bit of JS in the mounted hook of the component to add targetted and dynamic styles.
First we will need to constrain dynamic styles to this element. We can use the internal id of the created component this._uid, attaching to scope the css. (Note this is internal API so can be subject to change)
<template>
<div class="image" :data-style-scope="_uid">
</div>
</template>
The next part is to generate the style in a computed property, to later inject into a style block. You can expand on this computed property, to conditionaly assign properties ect. Note: keep the properties to the dynamic values only.
css () {
const selector = `.image[data-style-scope="${this._uid}"]`
const img = val => `${selector} { background-image: url("${val}"); }`
const sm = img(this.sm)
const md = img(this.md)
const lg = img(this.lg)
return `
${sm}
#media (min-width: 200px) { ${md} }
#media (min-width: 300px) { ${lg} }
`
}
This generated string from the css computed property is what we will now use when creating the style tag at mount. At mount we create a style node and append to the head. Assigning the nodes to the vm for references.
Using the references in the vm we can watch changes to the computed updating the style node.
Remember to clean up before destorying the component, removing the style node.
{
data () {
return {
// Reference data properties
style: null,
styleRef: null
}
},
mounted () {
// Create style node
let style = document.createElement('style')
style.type = "text/css"
style.appendChild(document.createTextNode(''))
// Assign references on vm
this.styleRef = style
this.style = style.childNodes[0]
// Assign css the the style node
this.style.textContent = this.css
// Append to the head
document.head.appendChild(style)
},
beforeDestroy () {
// Remove the style node from the head
this.style.parentElement.removeChild(this.style)
},
computed: {
css () {
// ...
}
},
watch: {
css (value) {
// On css value change update style content
this.style.textContent = this.css
}
}
}
Working Example: https://jsfiddle.net/bLkc51Lz/4/
You could also try the module described here: https://alligator.io/vuejs/vue-responsive-components/ which is called vue-responsive-components
It lets the component change its CSS depending on its own width (not on the entire browser's width)

How to add a class to an element when another element gets a class in angular?

I have a scrollspy directive that adds an ".active" class to a nav item. When the first nav item has the ".active" class I want my header bar to contain a certain class too. Attached is a simplified example, but how can I add ".active" to item 1 by only looking at the classes in item 2. jsfiddle
<div ng-app>
<div ng-controller='ctrl'>
<div id="item1" ng-class="if item2 has class=active then add active class here">Item 1</div>
<div id="item2" ng-class="myVar">Item 2</div>
</div>
//I can't use a scope object I can only look at item 2's classes
<button type="button" ng-click="myVar='active'">Add Class</button>
<button type="button" ng-click="myVar=''">Remove Class</button>
Click here for live demo.
You'll need a directive to interact with the element. I would have the directive watch the element's classes and have it call a function from your controller when the classes change. Then, your controller function can apply the logic specific to your need, which is to set a flag letting another element know how to respond.
angular.module('myApp', [])
.controller('MyCtrl', function($scope) {
$scope.foo = function(classes) {
if (~classes.indexOf('active')) {
$scope.otherItemIsActive = true;
}
};
})
.directive('onClassChange', function() {
return {
scope: {
onClassChange: '='
},
link: function($scope, $element) {
$scope.$watch(function() {
return $element[0].className;
}, function(className) {
$scope.onClassChange(className.split(' '));
});
}
};
})
;

Why Does Turn.js Only Work Once in Meteor Application?

I want to integrate Turn.js in a meteor project, but come across a "small" problem ,
the script work well the first time I "load" the template , but wouldn't work when i come across the same template.
{{#if correspondances_readingMode}}
<script >
function loadApp() {
// Create the flipbook
$('.flipbook').turn({
// Width
width:922,
// Height
height:600,
// Elevation
elevation: 50,
// Enable gradients
gradients: true,
// Auto center this flipbook
autoCenter: true
});
}
// Load the HTML4 version if there's not CSS transform
yepnope({
test : Modernizr.csstransforms,
yep: ['../../lib/turn.js'],
nope: ['../../lib/turn.html4.min.js'],
both: ['css/basic.css'],
complete: loadApp
});
</script>
<style>
.page{
width:400px;
height:300px;
background-color:white;
line-height:300px;
font-size:20px;
text-align:center;
}
</style>
<div class="flipbook">
{{#each myPost}}
<div class="page">
{{{text}}}
</div>
{{/each}}
</div>
{{/if}}
All seems to go as if the script was only executed when the user come across the template the first time , but wouldn't launch again the second time.
I have try many thing, but I came to think it's because of the handlebar {{#if}}
P.s :
On chrome the second time it's loaded it doesn't show turn.js as a script :
I was running into the same problem. I figured that the width of the booklet was calculated before the containing div got its full width. I set a delay of 1 second after rendering and now it seems to work fine.
Template.menu.rendered = function(){
setTimeout(function() {
import '/imports/turn.min.js';
$(window).ready(function() {
$('#magazine').turn({
display: 'double',
acceleration: true,
gradients: !$.isTouch,
elevation:50,
when: {
turned: function(e, page) {
// console.log('Current view: ', $(this).turn('view'));
}
}
});
});
$(window).bind('keydown', function(e){
if (e.keyCode==37)
$('#magazine').turn('previous');
else if (e.keyCode==39)
$('#magazine').turn('next');
});
}, 1000);
};
`

show the tooltip only when ellipsis is active

I have the next div:
<div class="div-class" style="width:158px;text-overflow:ellipsis;overflow:hidden;white-space:nowrap;" title=<%=myDesc%>
How can I show the tooltip only when ellipsis is active?
I find this function
function isEllipsisActive(e) {
return (e.offsetWidth < e.scrollWidth);
}
But I didn't know how to use it knowing I use jsp and struts
Try something like this:
Working DEMO
Working DEMO - with tooltip
$(function() {
$('div').each(function(i) {
if (isEllipsisActive(this))
//Enable tooltip
else
//Disable tooltip
});
});
function isEllipsisActive(e) {
return (e.offsetWidth < e.scrollWidth);
}
For anyone using qtip (being quite popular).
First, add a class to each of your overflowing elements.
<span class="ellipsis-text">Some very long text that will overflow</span>
Then, use the jQuery selector to select multiple such elements, and apply the qTip plugin (or any other tooltip that comes to mind) on to your elements as such:
$('.ellipsis-text').each(function() {
if (this.offsetWidth < this.scrollWidth) {
$(this).qtip({
content: {
text: $(this).text()
},
position: {
at: 'bottom center',
my: 'top center'
},
style: {
classes: 'qtip-bootstrap', //Any style you want
}
});
}
});

Resources