AngularJS how to run javascript after scope change? - javascript

Hi I had some Java scripts specific to a view. However, the script doesnt execute when angularjs loads the view. First time script run but script didnt execute when changed scope .The main index.html dont include this javascript code. This code in home.html . Index.html loads home.html but only one time working this javascript code.
$('#layerslider').layerSlider({
skin : 'fullwidth',
hoverPrevNext : true,
navStartStop : false,
navButtons : false,
autoPlayVideos : false,
animateFirstLayer : false
});
var $carousel = $('.recent-blog-jc, .recent-work-jc');
var scrollCount;
function adjustScrollCount() {
if( $(window).width() < 768 ) {
scrollCount = 1;
} else {
scrollCount = 3;
}
}
function adjustCarouselHeight() {
$carousel.each(function() {
var $this = $(this);
var maxHeight = -1;
$this.find('li').each(function() {
maxHeight = maxHeight > $(this).height() ? maxHeight : $(this).height();
});
$this.height(maxHeight);
});
}
function initCarousel() {
adjustCarouselHeight();
adjustScrollCount();
var i = 0;
var g = {};
$carousel.each(function() {
i++;
var $this = $(this);
g[i] = $this.jcarousel({
animation : 600,
scroll : scrollCount
});
$this.jcarousel('scroll', 0);
$this.prev().find('.jcarousel-prev').bind('active.jcarouselcontrol', function() {
$(this).addClass('active');
}).bind('inactive.jcarouselcontrol', function() {
$(this).removeClass('active');
}).jcarouselControl({
target: '-='+scrollCount,
carousel: g[i]
});
$this.prev().find('.jcarousel-next').bind('active.jcarouselcontrol', function() {
$(this).addClass('active');
}).bind('inactive.jcarouselcontrol', function() {
$(this).removeClass('active');
}).jcarouselControl({
target: '+='+scrollCount,
carousel: g[i]
});
$this.touchwipe({
wipeLeft: function() {
$this.jcarousel('scroll','+='+scrollCount);
},
wipeRight: function() {
$this.jcarousel('scroll','-='+scrollCount);
}
});
});
}
$(function(){
$(window).load(function(){
initCarousel();
});
});
$(window).resize(function () {
$carousel.each(function() {
var $this = $(this);
$this.jcarousel('destroy');
});
initCarousel();
});

Just add $scope.$apply() as close to the async event as possible, though keep in mind this is not best practice (you should try to do everything you can "the Angular way").

I fix this problem with angular directive. I get element with angular.element(document.querySelector('....')). I used ng-repeat in the directive template.
directive('carousel', function () {
return {
restrict: 'A',
replace: true,
transclude: false,
template: ' <div class="blank floated"><div class="four columns carousel-intro"><section class="entire"><h3>{{homepage.header4}}</h3><p>{{homepage.text4}}</p></section><div class="carousel-navi"><div id="work-prev" class="arl active jcarousel-prev"><i class="icon-chevron-left"></i></div><div id="work-next" class="arr active jcarousel-next"><i class="icon-chevron-right"></i></div></div><div class="clearfix"></div></div><section class="jcarousel recent-work-jc"><ul><li class="four columns" ng-repeat="work in works"><h5>{{work.title}}</h5><span>{{work.type}}</span></figcaption></figure></li></ul></section></div>',
link: function link(scope, element, attrs) {
var container = $(element);
var carousel = container.children('.jcarousel')
carousel.jcarousel({
wrap: 'circular'
});
scope.$watch(attrs.images, function (value) {
carousel.jcarousel('reload');
});
angular.element(document.querySelector('#work-prev')).children('.jcarousel-control-prev')
.jcarouselControl({
target: '-=1'
});
angular.element(document.querySelector('#work-next')).children('.jcarousel-control-next')
.jcarouselControl({
target: '-=1'
});
}
}
});

Related

slitslider.js - open a specific div, not with arrow

I'm using Slit Slider js. This opens div slides with arrows and dots for navigation. Is there a way to create a link to open a specific slide? For example: Home, About Us etc. instead of arrows.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
$(function() {
var Page = (function() {
var $navArrows = $('#nav-arrows'),
$nav = $('#nav-dots > span'),
slitslider = $('#slider').slitslider({
onBeforeChange: function(slide, pos) {
$nav.removeClass('nav-dot-current');
$nav.eq(pos).addClass('na```v-dot-current');
}
}),
init = function() {
initEvents();
},
initEvents = function() {
// add navigation events
$navArrows.children(':last').on('click', function() {
slitslider.next();
return false;
});
$navArrows.children(':first').on('click', function() {
slitslider.previous();
return false;
});
$nav.each(function(i) {
$(this).on('click', function(event) {
var $dot = $(this);
if (!slitslider.isActive()) {
$nav.removeClass('nav-dot-current');
$dot.addClass('nav-dot-current');
}
slitslider.jump(i + 1);
return false;
});
});
};
return {
init: init
};
})();
Page.init();
});
Thanks for your support :)

Function in external javascript file called only on reload In react js

I have a external js file linked to my html and bundle.js file generated by webpack linked to html .
In index.html code is
<script src="js/main.js"></script>
<script type="text/javascript" src="bundle.min.js"></script>`
The issue is functions in main.js are called only once on page load in reactjs after running webpack and code is bundled.
main.js file code is
(function () {
'use strict';
var isMobile = {
Android: function() {
return navigator.userAgent.match(/Android/i);
},
BlackBerry: function() {
return navigator.userAgent.match(/BlackBerry/i);
},
iOS: function() {
return navigator.userAgent.match(/iPhone|iPad|iPod/i);
},
Opera: function() {
return navigator.userAgent.match(/Opera Mini/i);
},
Windows: function() {
return navigator.userAgent.match(/IEMobile/i);
},
any: function() {
return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
}
};
var mobileMenuOutsideClick = function() {
$(document).click(function (e) {
var container = $("#fh5co-offcanvas, .js-fh5co-nav-toggle");
if (!container.is(e.target) && container.has(e.target).length === 0) {
if ( $('body').hasClass('offcanvas') ) {
$('body').removeClass('offcanvas');
$('.js-fh5co-nav-toggle').removeClass('active');
}
}
});
};
var offcanvasMenu = function() {
$('#page').prepend('<div id="fh5co-offcanvas" />');
$('#page').prepend('<i></i>');
var clone1 = $('.menu-1 > ul').clone();
$('#fh5co-offcanvas').append(clone1);
var clone2 = $('.menu-2 > ul').clone();
$('#fh5co-offcanvas').append(clone2);
$('#fh5co-offcanvas .has-dropdown').addClass('offcanvas-has-dropdown');
$('#fh5co-offcanvas')
.find('li')
.removeClass('has-dropdown');
// Hover dropdown menu on mobile
$('.offcanvas-has-dropdown').mouseenter(function(){
var $this = $(this);
$this
.addClass('active')
.find('ul')
.slideDown(500, 'easeOutExpo');
}).mouseleave(function(){
var $this = $(this);
$this
.removeClass('active')
.find('ul')
.slideUp(500, 'easeOutExpo');
});
$(window).resize(function(){
if ( $('body').hasClass('offcanvas') ) {
$('body').removeClass('offcanvas');
$('.js-fh5co-nav-toggle').removeClass('active');
}
});
};
var burgerMenu = function() {
$('body').on('click', '.js-fh5co-nav-toggle', function(event){
var $this = $(this);
if ( $('body').hasClass('overflow offcanvas') ) {
$('body').removeClass('overflow offcanvas');
} else {
$('body').addClass('overflow offcanvas');
}
$this.toggleClass('active');
event.preventDefault();
});
};
var fullHeight = function() {
if ( !isMobile.any() ) {
$('.js-fullheight').css('height', $(window).height());
$(window).resize(function(){
$('.js-fullheight').css('height', $(window).height());
});
}
};
var contentWayPoint = function() {
var i = 0;
$('.animate-box').waypoint( function( direction ) {
if( direction === 'down' && !$(this.element).hasClass('animated-fast') ) {
i++;
$(this.element).addClass('item-animate');
setTimeout(function(){
$('body .animate-box.item-animate').each(function(k){
var el = $(this);
setTimeout( function () {
var effect = el.data('animate-effect');
if ( effect === 'fadeIn') {
el.addClass('fadeIn animated-fast');
} else if ( effect === 'fadeInLeft') {
el.addClass('fadeInLeft animated-fast');
} else if ( effect === 'fadeInRight') {
el.addClass('fadeInRight animated-fast');
} else {
el.addClass('fadeInUp animated-fast');
}
el.removeClass('item-animate');
}, k * 200, 'easeInOutExpo' );
});
}, 100);
}
} , { offset: '85%' } );
};
var dropdown = function() {
$('.has-dropdown').mouseenter(function(){
var $this = $(this);
$this
.find('.dropdown')
.css('display', 'block')
.addClass('animated-fast fadeInUpMenu');
}).mouseleave(function(){
var $this = $(this);
$this
.find('.dropdown')
.css('display', 'none')
.removeClass('animated-fast fadeInUpMenu');
});
};
var goToTop = function() {
$('.js-gotop').on('click', function(event){
event.preventDefault();
$('html, body').animate({
scrollTop: $('html').offset().top
}, 500, 'easeInOutExpo');
return false;
});
$(window).scroll(function(){
var $win = $(window);
if ($win.scrollTop() > 200) {
$('.js-top').addClass('active');
} else {
$('.js-top').removeClass('active');
}
});
};
// Loading page
var loaderPage = function() {
$(".fh5co-loader").fadeOut("slow");
};
var counter = function() {
$('.js-counter').countTo({
formatter: function (value, options) {
return value.toFixed(options.decimals);
},
});
};
var counterWayPoint = function() {
if ($('#fh5co-counter').length > 0 ) {
$('#fh5co-counter').waypoint( function( direction ) {
if( direction === 'down' && !$(this.element).hasClass('animated') ) {
setTimeout( counter , 400);
$(this.element).addClass('animated');
}
} , { offset: '90%' } );
}
};
var parallax = function() {
if ( !isMobile.any() ) {
$(window).stellar({
horizontalScrolling: false,
hideDistantElements: false,
responsive: true
});
}
};
var testimonialCarousel = function(){
var owl = $('.owl-carousel-fullwidth');
owl.owlCarousel({
items: 1,
loop: true,
margin: 0,
nav: false,
dots: true,
smartSpeed: 800,
autoHeight: true
});
};
var sliderMain = function() {
$('#fh5co-hero .flexslider').flexslider({
animation: "fade",
slideshowSpeed: 5000,
directionNav: true,
start: function(){
setTimeout(function(){
$('.slider-text').removeClass('animated fadeInUp');
$('.flex-active-slide').find('.slider-text').addClass('animated fadeInUp');
}, 500);
},
before: function(){
setTimeout(function(){
$('.slider-text').removeClass('animated fadeInUp');
$('.flex-active-slide').find('.slider-text').addClass('animated fadeInUp');
}, 500);
}
});
$('#fh5co-hero .flexslider .slides > li').css('height', $(window).height());
$(window).resize(function(){
$('#fh5co-hero .flexslider .slides > li').css('height', $(window).height());
});
};
$(function(){
mobileMenuOutsideClick();
offcanvasMenu();
burgerMenu();
contentWayPoint();
sliderMain();
dropdown();
goToTop();
loaderPage();
counterWayPoint();
counter();
parallax();
testimonialCarousel();
fullHeight();
});
}());
I want my code in main.js called always not only on reload. I am using reactjs and webpack.
Please help me fix this. Thank you.
Please note that you your code in main.js is wrapped in something like this:
(function () {
...
}());
Above construction is called Immediately-Invoked Function Expression (IIFE) - it makes code inside to be called immediately and because everything defined inside any function is visible only in this function (is not visible outside function scope) it also helps to not pollute global context. You can read more about it here.
If you want to have possibility to call it anytime you need you should use normal function (not IIFE):
function mainFunction() {
//your codde
}
and then you can call it anytime you need (also on page load).

JQuery Set tab to "active"

How can I modify this jsfiddle so that it will:
a) highlight the active <li>
b) Make it possible to activate a tab content at page load (a tab is already opened when the page is loaded for the first time)
Thank you!
$(document).ready(function() {
var $panels = $('.panels > .panel');
$('#menu > li').on('click', 'a', function() {
$panels.filter('.'+this.id).trigger('togglePanel');
});
$panels
.on('togglePanel', function(){
var $this = $(this)
, $activePanels = $panels.filter(':visible').not($this);
if ($activePanels.length) {
$activePanels
.one('panelHidden', function(){
$this.is(':visible')
? $this.trigger('hidePanel')
: $this.trigger('showPanel');
})
.trigger('hidePanel');
} else {
$this.is(':visible')
? $this.trigger('hidePanel')
: $this.trigger('showPanel');
}
})
.on('hidePanel', function(){
var $this = $(this);
$this.find('.content').fadeOut(500, function() {
$this.animate({
'width': 'hide'
}, 1000, function(){
$this.trigger('panelHidden');
});
});
})
.on('showPanel', function(){
var $this = $(this);
$this.animate({
'width': 'show'
}, 1000, function() {
$this.find('.content').fadeIn(500, function(){
$this.trigger('panelShown');
});
});
});
$panels.find('.content .close').on('click', function() {
$(this).closest('.panel').trigger('togglePanel');
});
});

How to make every page have swipe method by using loop?

I'm newbie here. I was try to make every single page have a swipe method for jQuery mobile site as below:
$("#page1").swipeleft(function () {
$.mobile.changePage("#page2", {
transition: "slide"
});
});
$("#page2").swipeleft(function () {
$.mobile.changePage("#page3", {
transition: "slide"
});
});
when i try to make a loop like this it doesn't work.
var i = 1;
if(i <= 3;) {
$("#page" + i).swipeleft(function () {
$.mobile.changePage("#page" + (i + 1), {
transition: "slide"
});
});
};
something missing for my code?
updated: tried this code but seem doesn't work
for (var i = 1; i<=3; i++) {
$("#page"+i).swipeleft(function () {
$.mobile.changePage("#page"+(i+1), {
transition: "slide"
});
});
}
here is my code:
http://jsfiddle.net/lansinz/FHnp6/1/
You don't actually seem to a loop in your code. Try the following
//Create a loop for pages 1 to 3
for (var i = 1; i <= 3; i++) {
//When page is 'swiped' call the nextPage() function
$('#page' + i).on('swipeleft', nextPage);
}
function nextPage(event) {
//Get the ID attribute of the element swiped
var id = $(event.target).attr('id');
//Get the number at the end of the elements ID (to work out the page number)
var pageNo = parseInt(id.substr(4), 10);
//Call the changePage function, increasing the page number by one
$.mobile.changePage($('#page' + (pageNo + 1)), {
transition: 'slide'
});
}
jsFiddle Link
try this simple way...
$(document).on("swipeleft", '#'+event.target.id, function () {
var nextpage = $(this).next('div[data-role="page"]');
if (nextpage.length > 0) {
alert(nextpage.attr('id'));
$.mobile.changePage(nextpage, "slide", false, true);
}
});
$(document).on("swiperight", '#'+event.target.id, function () {
var prevpage = $(this).prev('div[data-role="page"]');
if (prevpage.length > 0) {
$.mobile.changePage(prevpage, { transition: "slide", reverse: true }, true, true);
}
});
Or the old school way of doing it with lengthy code :)
$(document).on('pageshow', '#page1', function(){
$( "#page1" ).on( 'swipeleft', function(){
$.mobile.changePage('#page2');
});
});
$(document).on('pageshow', '#page2', function(){
$( "#page2" ).on( 'swipeleft', function(){
$.mobile.changePage('#page3');
});
$( "#page2" ).on( 'swiperight', function(){
$.mobile.changePage('#page1');
});
});
$(document).on('pageshow', '#page3', function(){
$( "#page3" ).on( 'swiperight', function(){
$.mobile.changePage('#page2');
});
});

Rollover delay for Map markers

We had a developer work-up a piece of javascript for animating markers on a map for us. See http://luniablue.com/clients/endowment for it's current state.
The issue I'm having, is that the rollover is too sensitive and I want there to be a 1sec pause before executing the rollover function. From what I've read, I need to declare a setTimeout() function, but I'm not clear on where to insert that.
I have tried every place that I can see and I've had no luck except in breaking the script. I'm sure it's something stupid simple, but javascript isn't my stong point. Can anyone help me out?
Here's the code:
var firstEntry = true;
var lastOn = '';
function showAllPins() {
if ($('#communities').hasClass('theMouseIsOff')) {
var citiesArr = [];
$('.pin').each( function () {
citiesArr.push(this.id);
$('#'+this.id).hide();
});
var stillHidden = citiesArr.length;
while (stillHidden > 0) {
var a = Math.floor(Math.random()*citiesArr.length);
if ($('#'+citiesArr[a]).is(':hidden')) {
$('#'+citiesArr[a]).show().delay(Math.floor(Math.random()*900)).animate({
opacity: 1,
top: '+=40',
}, Math.floor(Math.random()*900), 'easeOutBounce');
stillHidden--;
}
}
firstEntry = true;
$('#communities').removeClass('theMouseIsOff');
}
}
function showPin(relid){
lastOn = relid;
if ($('#communities').hasClass('theMouseIsOff')) $('#communities').removeClass('theMouseIsOff');
if (firstEntry == true) {
$("#communities div[id!=" + relid + "].pin").animate({
opacity: 0,
top: '-=40',
}, 500);
firstEntry = false;
} else {
$("#communities div[id=" + relid + "].pin").animate({
opacity: 1,
top: '+=40',
}, 500, 'easeOutBounce');
}
}
function removeLastPin() {
$('#communities').addClass('theMouseIsOff');
$("#communities div[id=" + lastOn + "].pin").animate({
opacity: 0,
top: '-=40',
}, 500);
setTimeout('showAllPins()',600);
}
$(document).ready( function () {
$('.pin').mouseenter( function () {
relid = $(this).attr('rel');
showPin(relid);
}).mouseleave( function () { removeLastPin() });
});
$(document).ready(function() {
$('.pin').each(function() {
var selector = '#' + $(this).data('tooltip-id');
Tipped.create(this, $(selector)[0], { skin: 'light', hook: { target: 'topmiddle', tooltip: 'bottomleft'}});
});
});
Where you see:
$(document).ready( function () {
$('.pin').mouseenter( function () {
relid = $(this).attr('rel');
showPin(relid);
}).mouseleave( function () { removeLastPin() });
});
You can change it to:
$(document).ready( function () {
$('.pin').mouseenter( function () {
relid = $(this).attr('rel');
setTimeout(function(){showPin(relid)}, 1000);
}).mouseleave( function () { removeLastPin() });
});
By changing the showPin() function to execute after a timeout, the pin should appear after the specified interval.
Update:
If you would like the function only to run if the mouseleave hasn't occurred during the specified interval, you can clear the interval on mouseleave like this:
$(document).ready(function() {
$('.pin').mouseenter(function() {
relid = $(this).attr('rel');
var awaiting = setTimeout(function() {
showPin(relid)
}, 1000);
}).mouseleave(function() {
removeLastPin();
clearInterval(awaiting);
});
});

Categories