ng-animate to created a slideIn / slideOut transition - javascript

I am struggle to execute a simple slide transition using angular, i know how to do this perfectly using jquery, however i am trying make use of angular and it's tools. This here provides an example of what have done thus farClick Here for example - click on the link shop..
<div id="wrapper">
<header ng-app="menu" id="main-nav">
<ul id="nav" ng-controller="subNavController">
<li>search</li>
<li>
<a class="hiddenMenu" ng-click="navMenu = !navMenu">shop</a>
<div ng-show="navMenu" class="block"></div>
</li>
<li>Join LYB</li>
<li>LYB Mix Series</li>
<li>Help</li>
<li>Sign In</li>
<li>English</li>
</ul>
</header>
</div>
controller
var app = angular.module("menu", []);
app.controller("subNavController", function ($scope){
$scope.menu = function (){
$scope.navMenu = ! $scope.navMenu;
};
$scope.navMenu = false;
});
Does anyone know how to achieve a slide in effect using angular

Here is how I achieved a similar effect, but in my case it was sliding the div in from the top. You should be able to switch the few references to top to suit your case. This requires angular-animate, jQuery, and the class specified as the name of the animation to be applied to the element (.loading in my example).
app.animation('.loading', function() {
return {
addClass : function(element, className, done) {
if(className == 'ng-hide') {
jQuery(element).animate({
top: '-100px'
}, 1000, done);
}
else {
done();
}
},
removeClass : function(element, className, done) {
if(className == 'ng-hide') {
element.css('top','-100px');
/* remove it early so you can animate on it since
it is not possible using element.css() to set
a style using !important */
element.removeClass('ng-hide');
jQuery(element).animate({
top:0
}, 0, done);
}
else {
done();
}
}
};
});

Related

The way of triggering transition in Vue.js

I am trying to make transition in Vue, and I have a question how to trigger it.
I saw normally transition is triggered by v-show or v-if. but is there another way to execute?
I want to
・Keep my element's opacity as 0.2 and becomes 1 when the transition is triggered
・Also I am using The Element.getBoundingClientRect() to decide the area where transition should happen.
But obviously, v-show or v-if do not let me to do since they make the element disappear or display: none( so I can not measure the element by .getBoundingClientRect())
This is my template
<ul class="outer-wrapper" >
<li class="slide one" >
<div>
<a href="#">
<transition name="fade-animation">
<img v-show="show" ref="slider1" src="../assets/test.png">
</transition>
</a>
</div>
</li>
.
.
.
</ul>
and Vue script
export default {
name: 'test',
data(){
return{
show: false
}
},
methods: {
opacityChange: function () {
let slider = this.$refs.slider1.getBoundingClientRect();
let sliderLeft = Math.floor(slider.left);
let sliderRight = Math.floor(slider.right);
let centerPoint = Math.floor(window.innerWidth / 2);
let sliderWidth = slider.width;
if(sliderRight <= centerPoint + sliderWidth && sliderLeft >= centerPoint - sliderWidth) {
this.show = true;
} else {
this.show = false;
}
}
}
}
and css
.fade-animation-enter,
.fade-animation-enter-leave-to {
opacity: 0.2;
}
.fade-animation-enter-to,
.fade-animation-enter-leave {
opacity: 1;
}
.fade-animation-enter-active,
.fade-animation-enter-leave-active {
transition: opacity, transform 200ms ease-out;
}
Thanks for your help :)
I think you can use usual CSS transition (or JS in some cases) for this, not Vue transitions. Vue transitions are used for lists/appear/disappear. In any other cases it's better to use CSS/JS.
They wrote more about state transition here

How to prevent owlcarousel from destroying custom dots?

I am making a simple carousel using OwlCarousel 2.2.1 and I have run into a problem with custom dots. I have my custom list of categories which I wanted to behave like dots in carousel.
<ul class="category-list">
<li class="category-list__item active" data="1">
<span class="icon icon--red category-list__bg-icon"><svg>svg stuff here</svg></span>
<span class="icon icon--white category-list__main-icon"><svg>svg stuff here</svg></span>
<span class="category-list__title">Category 1</span>
</li>
...
<li class="category-list__item active" data="5">
<span class="icon icon--red category-list__bg-icon"><svg>svg stuff here</svg></span>
<span class="icon icon--white category-list__main-icon"><svg>svg stuff here</svg></span>
<span class="category-list__title">Category 5</span>
</li>
</ul>
My html:
<div class="vote-project__holder js-carousel-vote" data-owl-min-width="960">
<div class="row vote-project__duel">Content of slide 1</div>
...
<div class="row vote-project__duel">Content of slide 5</div>
</div>
In my carousel options I have binded them as dots using dotsContainer. This is my require.js part handling the carousel:
define(["jquery", "owlCarousel"], function($, owlCarousel) {
var OwlCarouselVote = {
init: function() {
var _this = this,
mainCarousel = $('.js-carousel-vote'),
minWidth = mainCarousel.data('owl-min-width') ? mainCarousel.data('owl-min-width') : 0;
if (window.matchMedia('(min-width: '+minWidth+ 'px)').matches) {
_this.initCarousel();
}
$(window).on('resize', function() {
if (mainCarousel.data("owlCarousel") !== "undefined") {
if (window.matchMedia('(min-width: '+minWidth+ 'px)').matches) {
_this.initCarousel();
} else {
_this.destroyCarousel();
}
}
});
},
destroyCarousel : function() {
jQuery('.js-carousel-vote').trigger('destroy.owl.carousel').removeClass("owl-carousel owl-loaded");
},
initCarousel: function () {
$('.js-carousel-vote').each(function() {
var $elm = $(this);
options = {
items: 1,
loop: false,
callbacks: true,
URLhashListener: true,
autoplay: false,
responsive: true,
margin: 50,
nav: true,
navSpeed: 500,
dots: true,
dotsContainer: '.category-list',
};
$elm.addClass("owl-carousel");
jQuery('.owl-carousel').owlCarousel(options);
});
//upon clicking on a category the carousel slides to corresponding slide
$('.category-list').on('click', 'li', function(e) {
jQuery('.owl-carousel').trigger('to.owl.carousel', [$(this).index(), 250]);
});
},
updateOnDomScan: function() {
this.init();
},
initOnDomScan: function() {
this.init();
}
};
return OwlCarouselVote;
});
The first part just decides wheter I am on mobile or desktop and then inits or destroys the carousel accordingly.
It works like a charm here, but on mobile, when I destroy the carousel like this jQuery('.js-carousel-vote').trigger('destroy.owl.carousel').removeClass("owl-carousel owl-loaded");, it destroys the whole .category-list list which I obviously need intact.
The reinitialization works fine because it leaves the inside of the carousel intact, but dots are missing because for some reason, the owlcarousel destroys them. I have no idea why it destroys HTML which does not belong to the carousel itself. I imagined when I binded the dots to my custom list that there is simply a reference to it and upon destroying the carousel, it would destroy just the reference.
To anyone interested, I haven't found a way to preserve native dots when destroyed. However I used a workaround so I created my own custom dots and used those.
I set dots: false in the carousel options and then binded my own list of dots to the carousel events like this
// This method listens to sliding and afterwards sets corresponding category to active
jQuery('.owl-carousel').on('translated.owl.carousel', function(event) {
$('.category-list li.active').removeClass('active');
//You have to set your li data attribute to the position it has in carousel
$('.category-list li[data-slide="'+ event.item.index +'"]').addClass("active");
});
//This method moves to corresponding slide upon clicking a category
$('.category-list').on('click', 'li', function(e) {
jQuery('.owl-carousel').trigger('to.owl.carousel', [$(this).index(), 250]);
});

Replace jQuery animation with Angular animation

One of my ng-views has a next structure
<div class="container-fluid wrapper">
<aside ng-if="asideMenu">
<div ng-include src="'html/partials/stats/aside.html'"></div>
</aside>
<section>
<div ng-include src="'html/partials/stats/grid.html'"></div>
<div ng-include src="'html/partials/stats/tabs.html'"></div>
</section>
where I have a grid and tabs as a major content and if user wants he can open aside bar. The function to open aside bar is
$scope.asideMenu = false;
$scope.aside = function () {
getTree();
var section = document.getElementsByTagName("section");
var aside = document.getElementsByTagName("aside");
$scope.asideMenu = !$scope.asideMenu;
if ($scope.asideMenu == true) {
$(section).animate({
'width': '84%'
}, 500, function () {
$(aside).animate({
'width': '15%'
});
});
}
else {
$(aside).animate({
'width': '0%'
}, 1000, function () {
$(section).animate({
'width': '100%'
});
});
}
};
So currently I'm using jQuery animation to open aside menu and shrink major content.
The question is simple, what is the best way to replace jQuery animation to Angular & CSS animation (without any additional dependencies and libs)??
This is simple example of my page

Don't ng-show element until ng-hide CSS transition is complete?

Simple question, but I'm having implementation troubles. If I have the following DOM setup:
<h1 class="fade" ng-repeat="child in parent.children" ng-show="parent.activeChild== child ">#{{ child.title }}</h1>
When the activeChild property of the parent model changes, how can I fade out the currently active child, before the model changes, and then fade in the newly active child post-change.
I have it working roughly, with just CSS transitions using this:
.fade.ng-hide-add {
transition:opacity 1s ease;
}
.fade.ng-hide-remove {
transition:opacity 1s ease 1s;
}
.fade.ng-hide-add {
opacity:1;
&.ng-hide-add-active {
opacity:0;
}
}
.fade.ng-hide-remove {
opacity:0;
&.ng-hide-remove-active {
opacity:1;
}
}
But, this ends up producing this problem (Plunkr):
Essentially, I want to chain my animation. I've tried reading the ng-animate docs, but I'm having trouble the syntax necessary to deliver the effect I want.
I've seen the Angular docs have something like this:
app.animation('.fade', [function() {
return {
addClass: function(element, className, doneFn) {
},
removeClass: function(element, className, doneFn) {
}
};
}]);
What is className? Is it the class I want to apply while fading in/out? The class I'm expecting?
What is doneFn meant to be? I assume it's a function that's run once the animation is complete? What goes in there?
What do I do in the addClass and removeClass function then, if I already have a doneFn?
The Goal
I'd like to generate a working animation directly using Angular's ngAnimate module, with either CSS or JS. How can I achieve this?
Why do you use a separate <h1> for each heading. You can use a single <h1> tag to show your heading.
I have created a demo for your problem and I have successfully done your requirement.
Updated
Note, codes are edited to use ngAnimate module. When you use ngAnimate module, it will create a class .ng-hide when you hide an element,
Here is the controller for your app,
app2.controller("testController", ["$scope", "$timeout", function ($scope, $timeout) {
$scope.heading = {};
$scope.heading.show = true;
$scope.parent = {};
$scope.parent.children = ["A", "B", "C", "D"];
$scope.parent.activeChild = "A";
$scope.changeHeading = function (child) {
$timeout(function () {
$scope.parent.activeChild = child;
$scope.heading.show = true;
}, 1000);
}
}]);
And your html page should be look like this,
<div ng-controller="testController">
<h1 class="myAnimateClass" ng-show="heading.show" ng-class="{fadeIn : heading.fadeInModel==true, fadeOut : heading.fadeOutModel}"> {{parent.activeChild}} </h1>
<p ng-repeat="child in parent.children" ng-click="heading.show = false;changeHeading(child)">{{child}}</p>
</div>
And I have used CSS3 to implement the fade in and fade out animation,
.myAnimateClass {
-webkit-transition: opacity 1s ease-in-out;
-moz-transition: opacity 1s ease-in-out;
-o-transition: opacity 1s ease-in-out;
-ms-transition: opacity 1s ease-in-out;
transition: opacity 1s ease-in-out;
opacity:1;
}
.myAnimateClass.ng-hide {
opacity: 0;
}
Explanation
To achieve your requirement, I have used ng-class and $timeout in angularJS.
You can see that, I have only one <h1> tag to display your heading. When I change the heading I just change it's binding property $scope.parent.activeChild.
And I have used two scope variables $scope.heading.fadeOutModel and $scope.heading.fadeInModel to add and remove classes fadeIn and fadeOut dynamically.
When user clicks to change the heading, I have added the class fadeOut to your heading. So, this will show an animation of fade out. And also I have fired a function in app.js, changeHeading().
You can see that, I forced the angular to wait for 1000 milliseconds to finish fade out animation. After this time, it will replace the selected heading to new one and add a class fadeIn. So, it will start animation for fade in.
Hope this will help you !!!
A more ng-animate way to show a specific element depending on a selection would be to use ngSwitch. This directive is used to conditionally swap DOM structure on your template based on a scope expression. Here is a example.
HTML
<button ng-repeat="item in items" ng-click="parent.selection = item">{{ item }}</button>
<div class="animate-switch-container" ng-switch on="parent.selection">
<div class="animate-switch" ng-switch-when="foo">foo</div>
<div class="animate-switch" ng-switch-when="bar">bar</div>
</div>
Javascript
$scope.items = ['foo', 'bar'];
$scope.parent = {
selection: $scope.items[0]
}
CSS
.animate-switch-container {
position:relative;
height:40px;
overflow:hidden;
}
.animate-switch {
padding:10px;
}
.animate-switch.ng-animate {
transition:opacity 1s ease;
}
.animate-switch.ng-leave.ng-leave-active,
.animate-switch.ng-enter {
opacity: 0;
}
.animate-switch.ng-leave,
.animate-switch.ng-enter.ng-enter-active {
opacity: 1;
}
This is not chaining, but it is a working animation directly using Angular's ngAnimate module. Also here is a example of it on angular's website.
You can use .animation to define animations that are Javascript based. For example, the functions you define as the values of addClass and removeClass
app.animation('.fade', [function() {
return {
addClass: function(element, className, doneFn) {
},
removeClass: function(element, className, doneFn) {
}
};
}]);
are called by Angular when it detects that you are adding or removing a class from an element, from one of the methods:
{{ }} interpoation in a template. E.g. <span class="{{shouldFade ? 'fade' : ''}}">....
Using ng-class in a template. E.g. <span ng-class="{fade: shouldFade}">...
Using the $animate service in a directive. E.g. $animate.addClass(element, 'fade') or $animate.removeClass(element, 'fade')
What is className? Is it the class I want to apply while fading in/out? The class I'm expecting?
In this example it will be fade. It a bit strange admittedly as in the example it is already clear this is the class name involved. However, if in the same digest cycle you're adding multiple classes to the same element, then the concatenation of them are passed as this string.
What is doneFn meant to be? I assume it's a function that's run once the animation is complete? What goes in there?
It's a function that you call once whatever Javascript animation you define is done. For example, to define an animation that does nothing as all:
addClass: function(element, className, doneFn) {
doneFn();
},
Calling it tells Angular that the animation has complete. This will, among other things, remove the ng-animate class from the element.
What do I do in the addClass and removeClass function then, if I already have a doneFn?
You put in them some code, perhaps using timeouts or a 3rd party library, to change the element somehow. When you have finished, you call doneFn. For example, a 1 step opacity "animation":
addClass: function(element, className, doneFn) {
element.css('opacity', 0.5);
setTimeout(function() {
doneFn();
}, 1000);
},
I'd like to generate a working animation directly using Angular's ngAnimate module, with either CSS or JS.
This doesn't really have much to do with the answers above! If I were doing a real-case, I strongly suspect I would position the elements absolutely, as anything else (that I can think of) at least, is a bit overly complicated.
However, if you do really want to chain the animations using ngAnimate, one possible way is to use the fact that $animate.addClass and $animate.removeClass returns a promise when it completes. In order to chain onto the end of such a promise returned when hiding an element, it must be called from some sort of central location, and keep track of which element is visible, being hidden, and being shown.
A way of doing this is to use 2 custom directives. One will be on each element to show and hide, that could be used very much like ngShow. The other will be a parent directive that will allow only one element to be visible at any time, and chain removal of the ng-hide class (and associated animations) after any addition of ng-hide. The directives will have to communicate, could be called something like ngShowUnique and ngShowUniqueController, such as in the following example.
<div ng-show-unique-controller>
<h1 class="fade" ng-repeat="child in parent.children" ng-show-unique="parent.activeChild == child">#{{child.title}}</h1>
</div>
and they could be implemented as below.
app.directive('ngShowUniqueController', function($q, $animate) {
return {
controller: function($scope, $element) {
var elements = [];
var expressions = [];
var watchers = [];
var unregisterWatchers = null;
var visibleElement = null;
function registerWatchers() {
unregisterWatchers = $scope.$watchGroup(expressions, function(vals) {
var newCurrentIndex = vals.indexOf(true);
var addPromise;
if (visibleElement) {
// Set a fixed height, as there is a brief interval between
// removal of this class and addition of another
$element.css('height', $element[0].getBoundingClientRect().height + 'px');
addPromise = $animate.addClass(visibleElement, 'ng-hide');
} else {
addPromise = $q.when();
}
visibleElement = elements[newCurrentIndex] || null;
if (!visibleElement) return;
addPromise.then(function() {
if (visibleElement) {
$animate.removeClass(visibleElement, 'ng-hide').then(function() {
$element.css('height', '');
});
}
})
});
}
this.register = function(element, expression) {
if (unregisterWatchers) unregisterWatchers();
elements.push(element[0]);
expressions.push(expression);
registerWatchers();
// Hide elements initially
$animate.addClass(element, 'ng-hide');
};
this.unregister = function(element) {
if (unregisterWatchers) unregisterWatchers();
var index = elements.indexOf(element[0]);
if (index > -1) {
elements.splice(index, 1);
expressions.splice(index, 1);
}
registerWatchers();
};
}
};
});
app.directive('ngShowUnique', function($animate) {
return {
require: '^ngShowUniqueController',
link: function(scope, element, attrs, ngShowUniqueController) {
ngShowUniqueController.register(element, function() {
return scope.$eval(attrs.ngShowUnique);
});
scope.$on('$destroy', function() {
ngShowUniqueController.unregister(element);
});
}
};
});
This can be seen at http://plnkr.co/edit/1eJUou4UaH6bnAN0nJn7?p=preview . I have to admit, it's all a bit faffy.
using ngRepeat that shows only one element at time, in my opinion, is a bad idea... because you're showing only one element!
you can use the parent.activeChild property directly...
Have a look on what follows:
Note: I did this snippet in just ten minutes, it's unoptimized and can have some bug... you can use it as starter :)
(function(window, angular, APP) {
APP
.value('menuObject', {
name: 'Main Navigation',
current: null,
children: [{
label: 'Don\'t ng-show element until ng-hide CSS transition is complete?',
url: 'http://stackoverflow.com/questions/33336249/dont-ng-show-element-until-ng-hide-css-transition-is-complete',
isCurrent: false
},
{
label: 'Hitmands - Linkedin',
url: 'http://it.linkedin.com/in/giuseppemandato',
isCurrent: false
},
{
label: 'Hitmands - Github',
url: 'https://github.com/hitmands',
isCurrent: false
},
{
label: 'Hitmands - StackOverflow',
url: 'http://stackoverflow.com/users/4099454/hitmands',
isCurrent: false
}
]})
.directive('menu', function(menuObject, $q) {
function menuCtrl($scope, $element) {
$scope.parent = menuObject;
this.getCurrentChild = function() {
return $scope.parent.current;
};
this.getDomContext = function() {
return $element;
};
this.setCurrentChild = function(child) {
return $q.when($scope.parent)
.then(function(parent) {
parent.current = child;
return parent;
})
.then(function(parent) {
return parent.children.forEach(function(item) {
item.isCurrent = child && (item.label === child.label);
});
})
};
}
return {
restrict: 'A',
templateUrl: 'embedded-menutemplate',
scope: {},
controller: menuCtrl
};
})
.directive('menuItem', function($animate, $q, $timeout) {
function menuItemPostLink(iScope, iElement, iAttributes, menuCtrl) {
iElement.bind('click', setCurrentTitle);
iScope.$on('$destroy', function() {
iElement.unbind('click', setCurrentTitle);
})
function setCurrentTitle(event) {
event.preventDefault();
var title;
return $q
.when(menuCtrl.getDomContext())
.then(function(_menuElement) {
title = angular.element(
_menuElement[0].querySelector('#menuItemCurrent')
);
})
.then(function() {
return title.addClass('fade-out');
})
.then(function() {
return $timeout(menuCtrl.setCurrentChild, 700, true, iScope.child);
})
.then(function() {
return title.removeClass('fade-out');
})
}
}
return {
require: '^menu',
link: menuItemPostLink,
restrict: 'A'
};
})
;
})(window, window.angular, window.angular.module('AngularAnimationExample', ['ngAnimate']));
nav {
text-align: center;
}
.link {
display: inline-block;
background-color: lightseagreen;
color: black;
padding: 5px 15px;
margin: 1em;
}
#menuItemCurrent {
padding: 1em;
text-transform: uppercase;
border: 1px solid black;
}
#menuItemCurrent span {
transition: 500ms opacity linear;
opacity: 1;
}
#menuItemCurrent.fade-out span {
opacity: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular-animate.js"></script>
<article ng-app="AngularAnimationExample">
<nav menu></nav>
<script id="embedded-menutemplate" type="text/ng-template">
<nav >
<a menu-item class="link" ng-repeat="child in parent.children track by $index" ng-bind="child.label" ng-href="{{ child.url }}"></a>
<h1 id="menuItemCurrent"><span ng-bind="parent.current.url || 'NoMenuCurrentSelected'"></span></h1>
{{ parent.current || json }}
</nav>
</script>
</article>
The problem is that H1 is a block level element that is positioned within it's parent and no overlap is allowed. That is why you see one animation that's disappearing pushing down the animation that is appearing.
You can see that this is happening more clearly here: Demo
To fix this, you want to keep the block level element H1, and make its position relative, so that it can keep its relative position in the overall flow of the page. Then set the child SPAN elements to have absolute positioning - absolute position relative to the parent H1. This allows all span elements to overlap each other.
CSS
.fade {
opacity: 1;
position: relative;
}
.fade.ng-hide-add {
transition:opacity 1s ease;
position: absolute;
}
.fade.ng-hide-remove {
transition:opacity 1s ease 1s;
position: absolute;
}
.fade.ng-hide-add {
opacity:1;
}
.fade.ng-hide-add.ng-hide-add-active {
opacity:0;
}
.fade.ng-hide-remove {
opacity:0;
}
.fade.ng-hide-remove.ng-hide-remove-active {
opacity:1;
}
HTML
<body ng-controller="MainCtrl">
<h1><span class="fade" ng-repeat="child in parent.children" ng-show="parent.activeChild == child ">#{{child.title}}</span></h1>
<button ng-repeat="child in parent.children" ng-click="parent.activeChild = child">{{ child.title }}</button>
</body>
There is one problem though... Since the SPAN elements have absolute positioning, it is removed from flow when animating, and the parent H1 can't resize to fit the SPAN contents. This causes the SPAN to jump unexpectedly.
The way to address this (and admittedly, it's a bit of a hack) is by adding an empty space after the SPAN repeater. So when the ngRepeat SPANS get pulled out of normal flow because of absolute positioning, the empty space which is outside the ngRepeat preserves the spacing of the H1.
Here is a working Plunker.
You might want to look into transitionend event which is supported by all modern browsers.
element.addEventListener('transitionend', callback, false);
Quick answer to this - To solve this problem in the past I have always positioned the content absolute. This way when the transition takes place it stays in the same position.
There is no other way around it because the content takes up space in the dom if its inline or inline-block which is why you see the jump until the transition is finished

Remove element at specific screen width with jquery?

I'm building a responsive site with a mobile first approach where i need to add a html element when the screen is larger than 641px and remove when less. The problem i'm having is when i resize my screen larger than 641px the code produces infinite numbers of said element and when i reduce the screen size there is masses amounts of space when they are removed.
my code looks like this:
<script>
$(function () {
$(window).resize(function () {
if ($(window).width() > 641) {
$('.project_nav').append('<li><a class="work_grid" href="#"><img src="images/noun_project_5193.svg"/> </a></li>');
} else {
$('.work_grid').remove();
}
});
});
</script>
And here's the html i want to append:
<div class="project_nav">
<ul>
<li><a class="up_arrow" href="#"><img src="images/noun_project_6978.svg"/> </a></li>
<li><a class="prev_arrow" href="#"><img src="images/noun_project_6976.svg"/> </a></li>
<li><a class="next_arrow" href="#"><img src="images/noun_project_6977.svg"/> </a></li>
</ul>
</div>
Any help is greatly appreciated!
You need to keep track of if the element has already been added or removed. Easiest way without pounding the dom is to store this in a variable:
$(function () {
var isAdded = false;
$(window).resize(function () {
if (!isAdded && $(window).width() > 641) {
isAdded = true;
$('.project_nav').append('<li class="work_grid_container"><a class="work_grid" href="#"><img src="images/noun_project_5193.svg"/> </a></li>');
} else if (isAdded && $(window).width() <= 641) {
isAdded = false;
$('.work_grid_container').remove();
}
});
});
This way it will only add the element if it hasn't already been added and it will remove it only if it currently exists on the page.
Note: You need to have a selector for the li instead of the a! Otherwise you will keep adding lis. You need to fully remove what you added.
What is happening is that when you resize, you are actually resizing a whole bunch, adding way too many elements. What you want to do is add some sort of Timeout. Here is an example.
$(window).resize(function () {
clearTimeout(window.refresh_size);
window.refresh_size = setTimeout(function () {
//Do stuff
}, 100);
This way, it will only do your code after you have stopped resizing the page for a least 100 ms.

Categories

Resources