basically I have an electron app and i've added minimize/close butttons to it
on load the buttons work but after switching page with smoothstate they stop working
i've found various solutions (github faq, stackoverlow, etc) but none worked so far
the buttons html
<div id="title-bar-btns">
<button class="btn btn-outline" id="min-btn">—</button>
<button class="btn btn-outline" id="close-btn">X</button>
</div>
the main.js
$(function() {
'use strict';
var $page = $('#main'),
options = {
debug: !0,
prefetch: !0,
cacheLength: 4,
onStart: {
duration: 350,
render: function($container) {
$container.addClass('is-exiting');
smoothState.restartCSSAnimations()
}
},
onReady: {
duration: 0,
render: function($container, $newContent) {
$container.removeClass('is-exiting');
$container.html($newContent)
initfunction();
}
},
onAfter: function($container, $newContent) {
initfunction();
}
},
smoothState = $page.smoothState(options).data('smoothState')
});
$(document).ready(function() {
initfunction();
});
function initfunction() {
(function() {
const {
BrowserWindow
} = require('electron').remote
function init() {
document.getElementById("min-btn").addEventListener("click", (e) => {
var window = BrowserWindow.getFocusedWindow();
window.minimize()
});
document.getElementById("close-btn").addEventListener("click", (e) => {
var window = BrowserWindow.getFocusedWindow();
window.close()
})
};
document.onreadystatechange = () => {
if (document.readyState == "complete") {
init()
}
}
})()
}
I have jquery flexslider which does slide animation. But the problem is the library is getting loaded before the DOM is loaded hence unable to trigger actions of flexslider.
Html:
<html>
<body>
<home-template></home-template>
<script src="./views/home-template.html" type=riot/tag></script>
<script src="bower_components/riot/riot+compiler.min.js" type="text/javascript"></script>
<script src="assets/js/vendor/jquery-1.11.2.min.js"></script>
<script src="assets/js/jquery.flexslider-min.js"></script>
<script>
riot.mount('*');
/***************** Flex Slider ******************/
$('#courses-slider').flexslider({
animation: "slide",
prevText: "",
nextText: "",
itemWidth: 292,
itemMargin: 0,
move: 1
}); // Courses Slider
</script>
</body>
</html>
In angular, I have fixed it like below:
.directive('flexslider', function () {
return {
link: function (scope, element, attrs) {
element.flexslider({
animation: "slide",
});
}
}
})
But how do I fix the same in riotjs?
Riot code:
<header-template></header-template>
<home-template></home-template>
<footer-template></footer-template>
<script>
var SharedMixin = {
observable: riot.observable()
};
//creating a data mixin so all tags can access data
var self = this;
var DataMixin = {
data: {
"status": "Init"
},
state: "home",
}
function goTo(path) {
if (path === 'home') {
console.log(path);
riot.mount('home-template', {class: 'loader'});
DataMixin.state = "home";
riot.update();
} else if (path === 'about') {
riot.mount('home-template');
DataMixin.state = "about";
riot.update();
} else if (path === 'instructors') {
riot.mount('instructors-template');
DataMixin.state = "instructors";
riot.update();
} else if (path === 'contact') {
riot.mount('contact-template');
DataMixin.state = "contact";
riot.update();
} else {
console.log("error");
}
}
riot.compile(function () {
// here tags are compiled and riot.mount works synchronously
//var tags = riot.mount('*')
//riot.route.exec(goTo);
header = riot.mount("header-template");
footer = riot.mount("footer-template");
riot.route(goTo);
riot.route.start(true);
});
riot.mixin(DataMixin);
</script>
you can call your flexslider plugin inside your riot tag, so that it's called on mount when dom is available :
<example-tag>
<p id="courses-slider">Est-ce que j'existe ?</p>
<script>
this.on('mount', function(){
$('#courses-slider').flexslider({
animation: "slide",
prevText: "",
nextText: "",
itemWidth: 292,
itemMargin: 0,
move: 1
}); // Courses Slider
});
</script>
</example-tag>
see http://riotjs.com/fr/guide/#montage
I'm using this code to match if href attribute starts with # and according to that to add class:
$('.navbar-nav a').each(function(index, element) {
if($(element).attr("href").match("^#"))
{
//Add class to inernal links
$(element).addClass("internal");
}
else
{
//Add class to external links
$(element).addClass("external");
}
});
Now I have problem to match if href starts with /#. I tried with '^/#' but it doesn't work.
I'll appreciate any help.
Update
Here is the whole code I'm using:
jQuery.noConflict();
(function( $ ) {
$(function() {
/*********************************************************************************************************/
/* -------------------------------------- Navigation ------------------------------------------ */
/*********************************************************************************************************/
//Add class to inernal and external links
$('.navbar-nav a').each(function(index, element) {
if($(element).attr("href").match(/^\/?#/))
{
//Add class to inernal links
$(element).addClass("internal");
}
else
{
//Add class to external links
$(element).addClass("external");
}
});
var lastId,
topMenu = $(".navbar-nav"),
topMenuHeight = topMenu.outerHeight(),
// All list items without external links
menuItems = topMenu.find("a").not(".external"),
// Anchors corresponding to menu items
scrollItems = menuItems.map(function() {
var item = $($(this).attr("href"));
if (item.length) {
return item;
}
});
// Bind click handler to menu items
// so we can get a fancy scroll animation
menuItems.click(function(e) {
if (!$(this).hasClass("dropdown-toggle")) {
var href = $(this).attr("href"),
offsetTop = href === "#" ? 0 : $(href).offset().top - topMenuHeight + 1;
$('html, body').stop().animate({
scrollTop: offsetTop
}, 1450, 'easeInOutQuart');
e.preventDefault();
}
});
// Bind to scroll
$(window).scroll(function() {
// Get container scroll position
var fromTop = $(this).scrollTop() + topMenuHeight;
// Get id of current scroll item
var cur = scrollItems.map(function() {
if ($(this).offset().top < fromTop)
return this;
});
// Get the id of the current element
cur = cur[cur.length - 1];
var id = cur && cur.length ? cur[0].id : "";
if (lastId !== id) {
lastId = id;
// Set/remove active class
menuItems
.parent().removeClass("active")
.end().filter("[href=#" + id + "]").parent().addClass("active");
}
});
/*********************************************************************************************************/
/* -------------------------------------- Home part - 100% hight ------------------------------------------ */
/*********************************************************************************************************/
jQuery.fn.refresh = function() {
var s = skrollr.get();
if (s) {
s.refresh(this);
}
return this;
};
function fullHeight() {
windowHeight = $(window).height();
$('#home, .tp-banner-container').css('height', windowHeight).refresh();
};
fullHeight();
$(window).resize(function() {
fullHeight();
});
/*********************************************************************************************************/
/* -------------------------------------- H2 big shadow ------------------------------------------ */
/*********************************************************************************************************/
$("h2").each(function () {
var h2 = $(this);
var span = h2.parent().find("span.title-shadow");
span.append(h2.html());
});
/*********************************************************************************************************/
/* -------------------------------------- Back to top ------------------------------------------ */
/*********************************************************************************************************/
$(".logo").click(function() {
$("html, body").animate({ scrollTop: 0 }, "easeInOutQuart");
return false;
});
/*********************************************************************************************************/
/* -------------------------------------- Contact form ------------------------------------------ */
/*********************************************************************************************************/
(function(e) {
function n(e, n) {
this.$form = e;
this.indexes = {};
this.options = t;
for (var r in n) {
if (this.$form.find("#" + r).length && typeof n[r] == "function") {
this.indexes[r] = n[r]
} else {
this.options[r] = n[r]
}
}
this.init()
}
var t = {
_error_class: "error",
_onValidateFail: function() {}
};
n.prototype = {
init: function() {
var e = this;
e.$form.on("submit", function(t) {
e.process();
if (e.hasErrors()) {
e.options._onValidateFail();
t.stopImmediatePropagation();
return false
}
return true
})
},
notEmpty: function(e) {
return e != "" ? true : false
},
isEmail: function(e) {
return /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(e)
},
isUrl: function(e) {
var t = new RegExp("(^(http[s]?:\\/\\/(www\\.)?|ftp:\\/\\/(www\\.)?|(www\\.)?))[\\w-]+(\\.[\\w-]+)+([\\w-.,#?^=%&:/~+#-]*[\\w#?^=%&;/~+#-])?", "gim");
return t.test(e)
},
elClass: "",
setClass: function(e) {
this.elClass = e
},
process: function() {
this._errors = {};
for (var t in this.indexes) {
this.$el = this.$form.find("#" + t);
if (this.$el.length) {
var n = e.proxy(this.indexes[t], this, e.trim(this.$el.val()))();
if (this.elClass) {
this.elClass.toggleClass(this.options._error_class, !n);
this.elClass = ""
} else {
this.$el.toggleClass(this.options._error_class, !n)
}
if (!n) {
this._errors[t] = n
}
}
this.$el = null
}
},
_errors: {},
hasErrors: function() {
return !e.isEmptyObject(this._errors)
}
};
e.fn.isValid = function(t) {
return this.each(function() {
var r = e(this);
if (!e.data(r, "is_valid")) {
e.data(r, "is_valid", new n(r, t))
}
})
}
})(jQuery)
/*********************************************************************************************************/
/* -------------------------------------- Ajax contact form ------------------------------------------ */
/*********************************************************************************************************/
$('#forms').isValid({
'name': function(data) {
this.setClass(this.$el.parent());
return this.notEmpty(data);
},
'email': function(data) {
this.setClass(this.$el.parent());
return this.isEmail(data);
},
'subject': function(data) {
this.setClass(this.$el.parent());
return this.notEmpty(data);
},
'message': function(data) {
this.setClass(this.$el.parent());
return this.notEmpty(data);
}
}).submit(function(e) {
e.preventDefault();
var $this = $(this);
$.ajax({
'url': $(this).attr('action'),
'type': 'POST',
'dataType': 'html',
'data': $(this).serialize()
}).done(function(response) {
$this.find('.notification').show();
$this.find('input[type="text"], input[type="email"], textarea').val('');
});
return false;
});
$('.notification').on('click', function() {
var $this = $(this);
$this.hide();
});
/*********************************************************************************************************/
/* -------------------------------------- Sticky navigation ------------------------------------------ */
/*********************************************************************************************************/
$("#navigation").sticky({
topSpacing: 0,
className: 'sticky',
wrapperClassName: 'main-menu-wrapper'
});
/*********************************************************************************************************/
/* -------------------------------------- Wow Scroll Animate ------------------------------------------ */
/*********************************************************************************************************/
wow = new WOW({
boxClass: 'wow',
animateClass: 'animated',
offset: 100,
movile: true
});
/*********************************************************************************************************/
/* -------------------------------------- Skrollr and Wow init ------------------------------------------ */
/*********************************************************************************************************/
if (!/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
//Skrollr
var s = skrollr.init({
edgeStrategy: 'set',
forceHeight: true,
smoothScrolling: true,
easing: {
wtf: Math.random,
inverted: function(p) {
return 1 - p;
}
}
});
//Wow init
wow.init();
}
/*********************************************************************************************************/
/* -------------------------------------- Charts, Skils ------------------------------------------ */
/*********************************************************************************************************/
$('.chart').waypoint(function() {
$(this).easyPieChart({
animate: 1000,
size: 200,
lineWidth: 5,
trackColor: "#fff",
barColor:"#de3926",
scaleColor: false,
size: 200,
onStep: function(from, to, percent) {
jQuery(this.el).find('.percent').text(Math.round(percent));
}
});
}, {
triggerOnce: true,
offset: 'bottom-in-view'
});
$(document).ready(function() {
/*********************************************************************************************************/
/* -------------------------------------- Ajax our team ------------------------------------------ */
/*********************************************************************************************************/
$('.ajax-popup-team').magnificPopup({
type: 'ajax',
showCloseBtn: true,
modal: true,
closeOnContentClick: false,
overflowY: 'scroll'
});
/*********************************************************************************************************/
/* -------------------------------------- Ajax portfolio page ------------------------------------------ */
/*********************************************************************************************************/
$('.ajax-popup-portfolio').magnificPopup({
type: 'ajax',
showCloseBtn: true,
modal: true,
closeOnContentClick: false,
overflowY: 'scroll',
gallery: {
enabled: true,
arrowMarkup: '<button title="%title%" type="button" class="portfolio mfp-arrow mfp-arrow-%dir%"></button>'
}
});
/*********************************************************************************************************/
/* -------------------------------------- Portfolio gallery ------------------------------------------ */
/*********************************************************************************************************/
$('.gallery-item-content').each(function() { // the containers for all your galleries
$(this).magnificPopup({
delegate: '.gallery-item', // the selector for gallery item
type: 'image',
gallery: {
enabled: true
}
});
});
/*********************************************************************************************************/
/* -------------------------------------- Video ------------------------------------------ */
/*********************************************************************************************************/
$('.popup-youtube, .popup-vimeo, .popup-gmaps').magnificPopup({
disableOn: 700,
type: 'iframe',
mainClass: 'mfp-fade',
removalDelay: 160,
preloader: true,
fixedContentPos: true
});
/*********************************************************************************************************/
/* -------------------------------------- Owl carousel ------------------------------------------ */
/*********************************************************************************************************/
$("#carousel-our-testimonials").owlCarousel({
autoPlay: 3000,
stopOnHover: true,
navigation: false,
paginationSpeed: 1000,
goToFirstSpeed: 2000,
singleItem: true,
autoHeight: true,
transitionStyle: "fade"
});
$("#carousel-our-clients").owlCarousel({
autoPlay: 10000,
stopOnHover: true,
navigation: true,
paginationSpeed: 1000,
goToFirstSpeed: 3500,
singleItem: false,
autoHeight: true,
transitionStyle: "fade",
navigationText: [
"<i class='fa fa-angle-left'></i>",
"<i class='fa fa-angle-right'></i>"
]
});
$("#blog-single").owlCarousel({
navigation: true, // Show next and prev buttons
pagination: false,
slideSpeed: 300,
paginationSpeed: 400,
navigationText: [
"<i class='fa fa-chevron-left'></i>",
"<i class='fa fa-chevron-right'></i>"
],
singleItem: true
});
/*********************************************************************************************************/
/* -------------------------------------- Dropdown Menu Fade ------------------------------------------ */
/*********************************************************************************************************/
$(".dropdown").hover(
function() {
$('.dropdown-menu', this).fadeIn(275);
$(this).addClass("open");
},
function() {
$('.dropdown-menu', this).fadeOut(275);
$(this).removeClass("open");
});
/*********************************************************************************************************/
/* -------------------------------------- Placeholder fix for IE ------------------------------------------ */
/*********************************************************************************************************/
(function($) {
if (!Modernizr.csstransforms3d) {
$('[placeholder]').focus(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
input.removeClass('placeholder');
}
}).blur(function() {
var input = $(this);
if (input.val() == '' || input.val() == input.attr('placeholder')) {
input.addClass('placeholder');
input.val(input.attr('placeholder'));
}
}).blur().parents('form').submit(function() {
$(this).find('[placeholder]').each(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
}
})
});
}
})
});
/*********************************************************************************************************/
/* -------------------------------------- Count ------------------------------------------ */
/*********************************************************************************************************/
$('#statistic').waypoint(function() {
$('.timer').countTo();
}, {
triggerOnce: true,
offset: 'bottom-in-view'
});
/*********************************************************************************************************/
/* -------------------------------------- Show and hide color-switcher ------------------------------------------ */
/*********************************************************************************************************/
$(".color-switcher .switcher-button").click(function(){
$( ".color-switcher" ).toggleClass("show-color-switcher", "hide-color-switcher", 800);
});
/*********************************************************************************************************/
/* -------------------------------------- Color Skins ------------------------------------------ */
/*********************************************************************************************************/
$('a.color').click(function(){
var title = $(this).attr('title');
$('#style-colors').attr('href', 'css/color-schemes/' + title + '.css');
return false;
});
/*********************************************************************************************************/
/* -------------------------------------- Loader ------------------------------------------ */
/*********************************************************************************************************/
$(window).load(function() {
$("#loader").delay(450).fadeOut(800);
$(".preload-gif").addClass('fadeOut');
});
});
})(jQuery);
If you want to match both, you could change the Regular expression to:
/^\/?#/
The question mark is a 0 or 1 quantifier, that will match whether there is 1 or no / at the beginning.
Check it out here: http://www.regexr.com/3ajoo
Also i used your code and tried to find the error you have: I think there is no error from the answer of this question. Your error must be something else. Try and wrap the function in $(document).ready() to make sure the DOM is loaded before searching the elements.
$(document).ready(function() {
$('.navbar-nav a').each(function(index, element) {
if ($(element).attr("href").match(/^\/?#/)) {
//Add class to inernal links
$(element).addClass("internal");
} else {
//Add class to external links
$(element).addClass("external");
}
});
});
.external {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class="navbar-nav">
Link
</li>
<li class="navbar-nav">
Link
</li>
<li class="navbar-nav">
Link
</li>
<li class="navbar-nav">
Link
</li>
<li class="navbar-nav">
Link
</li>
</ul>
Use / as delimiter.
if($(element).attr("href").match(/^\/#/))
So I have the code for fancybox:
$(".fancybox").fancybox({
beforeShow: function () {
var alt = this.element.find('img').attr('alt');
this.inner.find('img').attr('alt', alt);
this.title = alt;
}
});
and
$(document).ready(function () {
$(".fancybox").fancybox({
helpers: {
overlay: {
locked: false
}
}
});
});
when I try to use them both I get a syntax error:
$(document).ready(function () {
$(".fancybox").fancybox({
helpers: {
overlay: {
locked: false
}
}
beforeShow: function () {
var alt = this.element.find('img').attr('alt');
this.inner.find('img').attr('alt', alt);
this.title = alt;
}
});
});
and when I use them separately neither of the fancybox functions work.
<script>
$(document).ready(function () {
$(".fancybox").fancybox({
helpers: {
overlay: {
locked: false
}
}
});
});
</script>
<script>
$(".fancybox").fancybox({
beforeShow: function () {
var alt = this.element.find('img').attr('alt');
this.inner.find('img').attr('alt', alt);
this.title = alt;
}
});
</script>
How can I use them both?
You're missing a comma in your object properties on line 7 between helpers: { ... } and beforeShow: function() { ... }
$(document).ready(function () {
$(".fancybox").fancybox({
helpers: {
overlay: {
locked: false
}
}, // <-- this comma right here is missing in your code
beforeShow: function () {
var alt = this.element.find('img').attr('alt');
this.inner.find('img').attr('alt', alt);
this.title = alt;
}
});
});
I have a web application where I am trying to implement code for Session Timeout. I got a .js file that gives user choice to "continue with the current session" or "End Session" PB
However if user clicks on "continue with the current session" PB, session is still time out.
Please tell me what is wrong with this script: Here is the code
timeout-dialog.js:
String.prototype.format = function() {
var s = this,
i = arguments.length;
while (i--) {
s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
}
return s;
};
!function($) {
$.timeoutDialog = function(options) {
var settings = {
timeout: 1200,
countdown: 60,
title: 'Employee TimeOut Session',
message: 'Your session will expire in {0} seconds.',
question: 'press OK to remain logged in.',
keep_alive_button_text: 'Yes, Keep me signed in',
sign_out_button_text: 'No, Sign me out',
keep_alive_url: '/keep-alive',
logout_url: null,
logout_redirect_url: '/',
restart_on_yes: true,
dialog_width: 350
}
$.extend(settings, options);
var TimeoutDialog = {
init: function () {
this.setupDialogTimer();
},
setupDialogTimer: function() {
var self = this;
window.setTimeout(function() {
self.setupDialog();
}, (settings.timeout - settings.countdown) * 1000);
},
setupDialog: function() {
var self = this;
self.destroyDialog();
$('<div id="timeout-dialog">' +
'<p id="timeout-message">' + settings.message.format('<span id="timeout-countdown">' + settings.countdown + '</span>') + '</p>' +
'<p id="timeout-question">' + settings.question + '</p>' +
'</div>')
.appendTo('body')
.dialog({
modal: true,
width: settings.dialog_width,
minHeight: 'auto',
zIndex: 10000,
closeOnEscape: false,
draggable: false,
resizable: false,
dialogClass: 'timeout-dialog',
title: settings.title,
buttons : {
'keep-alive-button' : {
text: settings.keep_alive_button_text,
id: "timeout-keep-signin-btn",
click: function() {
self.keepAlive();
}
},
'sign-out-button' : {
text: settings.sign_out_button_text,
id: "timeout-sign-out-button",
click: function() {
self.signOut(true);
}
}
}
});
self.startCountdown();
},
destroyDialog: function() {
if ($("#timeout-dialog").length) {
$(this).dialog("close");
$('#timeout-dialog').remove();
}
},
startCountdown: function() {
var self = this,
counter = settings.countdown;
this.countdown = window.setInterval(function() {
counter -= 1;
$("#timeout-countdown").html(counter);
if (counter <= 0) {
//window.clearInterval(self.countdown);
self.signOut(false);
}
}, 1000);
},
keepAlive: function() {
var self = this;
this.destroyDialog();
//window.clearInterval(this.countdown);
$.get(settings.keep_alive_url, function(data) {
if (data == "OK") {
if (settings.restart_on_yes) {
self.setupDialogTimer();
}
}
else {
self.signOut(false);
}
});
},
signOut: function(is_forced) {
var self = this;
this.destroyDialog();
if (settings.logout_url != null) {
$.post(settings.logout_url, function(data){
self.redirectLogout(is_forced);
});
}
else {
self.redirectLogout(is_forced);
}
},
redirectLogout: function(is_forced){
var target = settings.logout_redirect_url + '?next=' + encodeURIComponent(window.location.pathname + window.location.search);
if (!is_forced)
target += '&timeout=t';
window.location = target;
}
};
TimeoutDialog.init();
};
}(window.jQuery);
.aspx code:
These are my reference in
<head>
<script src="Comm/jquery.min.js" type="text/javascript"></script>
<script src="Comm/jquery-ui.min.js" type="text/javascript"></script>
<script src="Comm/timeout-dialog.js" type="text/javascript"></script>
<link rel="stylesheet" href="css/timeout-dialog.css" type="text/css" media="screen, projection" />
</head>
In the<body> section
<body>
<script type="text/javascript">
var timeLeft = <%= Session.Timeout * 60 %>;
$(document).ready(function () {
$.timeoutDialog({ timeout: timeLeft, countdown: 10, logout_redirect_url: '../sessionLogout.htm', restart_on_yes: false });
});
</script>
....
....
</body>
Make sure your keep-alive url returns "OK" as it is what the code is looking for.
$.get(settings.keep_alive_url, function(data) {
if (data == "OK") {
if (settings.restart_on_yes) {
self.setupDialogTimer();
}
}
else {
self.signOut(false);
}