Files
dis-2019/js/scripts.js
2019-08-07 22:54:34 +02:00

902 lines
24 KiB
JavaScript

(function ($, root, undefined) {
$(function () {
'use strict';
// DOM ready, take it away
/* ========================================================================== */
/* VARIABLES */
/* ========================================================================== */
/* -------------------------------- geometry -------------------------------- */
const vw = $(window).width()
const wow = window.outerWidth
const wiw = window.innerWidth
const bw = $('body').width()
const wih = window.innerHeight
const vh = $(window).height()
const desktophomemargin = $(".header-1")[0].getBoundingClientRect().width
// height of scrollbar at bottom
const bottomScrollHeight = (_ => {
if (wih / vh > 1.5) {
return 0
} else {
let bs = wih - vh
return bs
}
})()
const cssWidths = {
vw: vw,
wow: wow,
wiw: wiw,
bw: bw,
desktophomemargin: desktophomemargin,
wih: wih,
vh: vh,
bottomScrollHeight: bottomScrollHeight
}
// console.log(cssWidths)
/* --------------------------- css values to vars --------------------------- */
//isMobile
const isMobile = (_ => {
if (wow < 769) {
//mobile settings
$('.social-link, .events-link').addClass('hidden')
return true
} else {
return false
}
})()
/**
* Checks if body has a class
* @param {string} classname The class to check
* @param {string} notclassname Optional: this classname makes it false
* @returns {boolean} True if body has that class, false if not OR it contains the notclassname
*/
function bodyHasClass(classname, notclassname) {
if ($('body').hasClass(classname)) {
if (notclassname) {
if ($('body').hasClass(notclassname)) {
return false
} else {
return true
}
} else {
return true
}
} else {
return false
}
}
//isHome
const isHome = bodyHasClass('home')
//isArchive
const isArchive = bodyHasClass('archive', 'category-esemeny')
//isSearch
const isSearch = bodyHasClass('search-results')
//isEsemeny
const isEsemeny = bodyHasClass('category-esemeny')
//isSingle
const isSingle = bodyHasClass('single')
var isMasonryPage = isArchive || isHome || isSearch
/* ========================================================================== */
/* FUNCTIONS */
/* ========================================================================== */
var rotateMenuButton = function () {
if ($(".menubutton button").hasClass("rotated")) {
$(".menubutton button").removeClass("rotated");
} else {
$(".menubutton button").addClass("rotated");
}
}
var showHideSocial = function () {
if (isMobile && $('.social-link').hasClass('hidden')) {
$('.social-link, .events-link').removeClass('hidden')
} else if (isMobile) {
$('.social-link, .events-link').addClass('hidden')
}
}
function convertRemToPixels(rem) {
return rem * parseFloat(getComputedStyle(document.documentElement).fontSize);
}
/* ========================================================================== */
/* SEARCH */
/* ========================================================================== */
// on mobile add to sidebar:
if (isMobile) {
$(".search-bar").prependTo("#sidebar-wrapper")
}
//clicking on desktop
if (!isMobile) {
$(".search-box button").click(function (e) {
// e.preventDefault()
var bar = $(this).next(".search-bar")
if (bar.hasClass("opensearch")) {
//if search is opened close:
bar.stop().animate({ width: "0" }, 400, function () {
bar.hide().removeClass("opensearch")
})
} else {
//if it's closed open:
bar.show().stop().animate({ width: wiw - (desktophomemargin * 3) }, 400, function () {
bar.addClass("opensearch")
$(".search-input").focus()
})
// console.log("calc(100% - " + (desktophomemargin * 2) + "px)")
}
})
}
/* ========================================================================== */
/* MENU */
/* ========================================================================== */
var menuWidth = wow
if (!isMobile) {
menuWidth = 500
}
$("#sidebar").simplerSidebar({
selectors: {
trigger: "#toggle-sidebar",
quitter: "#toggle-sidebar"
},
sidebar: {
width: menuWidth
},
mask: {
display: false,
css: {
backgroundColor: "black",
opacity: 1,
filter: "Alpha(opacity=100)" // IE opacity fix
}
},
gap: 0,
events: {
on: {
animation: {
both: rotateMenuButton
}
},
callbacks: {
animation: {
both: showHideSocial,
freezePage: false
}
}
}
});
/* -------------------------------------------------------------------------- */
/* HOME & ARCHIVES */
/* -------------------------------------------------------------------------- */
/* ----------------------------------- css ---------------------------------- */
if (!isMobile) {
if (isMasonryPage) {
//no overflowY
$('html').css({ overflowY: "hidden" })
//calculate wrappable elements
$('#content>*:not(.misha_loadmore)').addClass("hbox")
var wrapArticles = $(".hbox").length
//wrapping for big-small difference
if (isHome) {
$('.hbox:first-child').wrap('<div class="home_wrapper-big home_wrapper-1"></div>').addClass("home-big")
$('.hbox:nth-child(2)').wrap('<div class="home_wrapper-big home_wrapper-2"></div>').addClass("home-big")
wrapArticles = $(".hbox").length - 2
}
//add classes to articles and elements
var articleWrapCounter = 0
for (let i = 0; i < wrapArticles; i++) {
var j = i + 1
if (isHome) {
j = i + 3
}
if (i % 6 == 0) {
articleWrapCounter++
}
//console.log($('.hbox:nth-child(' + j + ')').attr("id"), i, j)
$('.hbox:nth-child(' + j + ')').addClass("home-small home-thumbnail-small-" + articleWrapCounter)
//change order if there is a description
if ($("body").is('.archive, .tag') && articleWrapCounter == 1) {
if (j == 3 || j == 4) {
$('.hbox:nth-child(' + j + ')').css({ order: j - 1 })
} else if (j == 5 || j == 6) {
$('.hbox:nth-child(' + j + ')').css({ order: j })
}
}
}
//wrap classes
for (let i = 0; i < articleWrapCounter; i++) {
var j = i + 1
if (isHome) {
j = i + 3
}
var k = i + 1
$(".home-thumbnail-small-" + k).wrapAll('<div class="home_wrapper-small home_wrapper-' + j + '"></div>')
if (i == 0) {
$(".home_wrapper-" + j).addClass("home_wrapper-s1")
}
}
//add bottom scrollbar to div on bottom:
if (bottomScrollHeight > 0) {
$(".home_wrapper-big .metadata").css({ bottom: bottomScrollHeight })
} else {
$(".home_wrapper-big .metadata").addClass("noBottomScrollbar")
}
//fit title
$(".archivetitle h1").fitText(0.6)
}//isMasonryPage end
}// !isMobile end
function random2() {
const choices = [
[1, 3],
[1, 5],
[1, 6],
[2, 4],
[2, 6],
[3, 4],
[3, 5],
[4, 6]
]
let nr = Math.floor(Math.random() * choices.length);
return choices[nr]
}
//jquery function, adds random class to 3 random cihldren
(function ($) {
$.fn.addRandomClasses = function () {
let rn = random2()
for (let i = 0; i < 2; i++) {
var j = rn[i]
this.children("article:nth-child(" + j + ")").addClass("random")
}
return this
};
})(jQuery);
$(".home_wrapper-small").each(function () {
$(this).addRandomClasses()
})
/* ----------------------------- Snap on mobile ----------------------------- */
// if (isMobile) {
// if (isMasonryPage) {
// $("article.post").SnapScroll({
// animateDuration: 400
// });
// }
// }
/* --------------------------------- To top --------------------------------- */
$(".totop>a").click(function (e) {
e.preventDefault()
$('html, body').stop().animate({ scrollTop: 0 }, 800);
})
/* ---------------------------- Scroll on desktop --------------------------- */
/**
* scroll to next or previous section
* @param {jQuery} target put here currElem
* @param {String} direction "next" of "prev"
*/
function homeScroll(target, direction) {
// console.log(target.attr('class'))
var nextelem;
if (direction == "next") {
nextelem = target.next()
} else {
nextelem = target.prev()
}
if (nextelem.length == 0) {
nextelem = target
}
var offset = ($(nextelem).position().left)
//if loadmore is the next, do not scroll, but load:
if (nextelem.attr("class") == "misha_loadmore") {
loadmore()
return target
} else {
//from the third wrap modify the offset
var wNum = parseInt($(nextelem).attr("class").split(" ")[1].split("-")[2])
if (wNum == 3 || !isHome) {
offset = offset - (desktophomemargin / 2)
} else if (wNum > 4 || !isHome) {
offset = offset - desktophomemargin
}
}
console.log("scrolling to: " + nextelem.attr("class") + " - offset: " + offset)
$('html, body, .wrapper').stop().animate({ scrollLeft: offset }, 800, function () {
//hide the left arrow if on start
if (nextelem.hasClass("home_wrapper-1")) {
$(".header-scroll-left").hide()
} else {
$(".header-scroll-left").show()
}
});
return nextelem;
}
//extractDelta(e): extract the scroll direction and length from an event
function extractDelta(e) {
if (e.wheelDelta) {
return e.wheelDelta;
}
if (e.originalEvent.detail) {
return e.originalEvent.detail;
}
if (e.originalEvent.deltaY) {
return e.originalEvent.deltaY * -1;
}
if (e.originalEvent && e.originalEvent.wheelDelta) {
return e.originalEvent.wheelDelta;
}
}
const selector = 'main>#content>div'
var currElem = $(selector + ':first-child')
//checking the current scroll location for refresh:
if (!isMobile) {
if (isMasonryPage) {
const homeDivWidths = []
const homeFullWidths = []
homeDivWidths[0] = 0
$(selector).each(function () {
homeDivWidths.push($(this)[0].getBoundingClientRect().width)
})
for (let i = 0; i < homeDivWidths.length; i++) {
let prev = homeFullWidths[i - 1]
if (i == 0) {
prev = 0
}
homeFullWidths[i] = homeDivWidths[i] + prev
}
// console.log(homeDivWidths)
// console.log(homeFullWidths)
var currscroll = $('html').scrollLeft()
var closest = homeFullWidths.reduce(function (prev, curr) {
return (Math.abs(curr - currscroll) < Math.abs(prev - currscroll) ? curr : prev);
});
var scrollnr = homeFullWidths.indexOf(closest) + 1
currElem = $(selector + ':nth-child(' + scrollnr + ')')
if (currElem.hasClass("home_wrapper-1")) {
$(".header-scroll-left").hide()
}
// console.log("currscroll", currscroll, "scrollnr", scrollnr, "closest", closest)
console.log("start location: " + currElem.attr("class"))
}
}
var scrolltimer = false;
$(window).on('wheel DOMMouseScroll', function (e) {
//e.preventDefault();
if (!isMobile) {
if (isMasonryPage) {
if (scrolltimer) {
return false;
}
scrolltimer = true;
setTimeout(() => {
scrolltimer = false;
}, 500);
var wd = extractDelta(e)
if (wd > 0) {
currElem = homeScroll(currElem, "prev")
}
else {
currElem = homeScroll(currElem, "next")
}
}
}
});
/* -------------------------- scroll click on home -------------------------- */
$(".header-scroll-left button").click(() => {
currElem = homeScroll(currElem, "prev")
})
$(".header-scroll-right button").click(() => {
currElem = homeScroll(currElem, "next")
})
/* --------------------------- scroll with keyboard --------------------------- */
var kd = false
$('html *:not(input)').keydown(function (event) {
if (kd) {
event.preventDefault();
return
} else {
if (!isMobile) {
if (isMasonryPage) {
if (!$('.search-bar *').is(':focus')) {
// console.log("keydown!")
kd = true
switch (event.which) {
case 40: //down
case 39: //right
case 74: //J
event.preventDefault();
currElem = homeScroll(currElem, "next")
break;
case 38: //up
case 37: //left
case 75: //K
event.preventDefault();
currElem = homeScroll(currElem, "prev")
break;
default:
break;
}
}
}
}
}
})
//check for keyup for disabling counter
$('html *:not(input)').keyup(function (event) {
if (!isMobile) {
if (isMasonryPage) {
if (!$('.search-bar *').is(':focus')) {
kd = false
}
}
}
})
/* -------------------------- loadmore: ajax loads -------------------------- */
$('.misha_loadmore').on("moreload-start", function () {
currElem = $(this).prev()
console.log("currelem: " + currElem.attr("class"))
})
$('.misha_loadmore').on("moreload-finish", function () {
//wrap new elements on load
articleWrapCounter++
var wrapnum = articleWrapCounter + 2
$("#content>article")
.addClass("home-small home-thumbnail-small-" + articleWrapCounter)
.wrapAll('<div class="home_wrapper-small home_wrapper-' + wrapnum + '"></div>')
$(".home_wrapper-" + wrapnum).addRandomClasses()
//Scroll to new element
currElem = homeScroll(currElem, "next")
})
/* ----------------------------- loadmore click ----------------------------- */
$('.misha_loadmore').click(function (e) {
e.preventDefault()
loadmore($(this))
});
var noMoreAjax = false
function loadmore(element) {
if (noMoreAjax) {
console.log("no more ajax")
return false
}
// var button = $(this),
var button = element || $('.misha_loadmore'),
data = {
'action': 'loadmore',
'query': misha_loadmore_params.posts, // that's how we get params from wp_localize_script() function
'page': misha_loadmore_params.current_page
};
// button.trigger("moreload-start")
$.ajax({ // you can also use $.post here
url: misha_loadmore_params.ajaxurl, // AJAX handler
data: data,
type: 'POST',
beforeSend: function (xhr) {
button.html('<p>Betöltés...</p>'); // change the button text, you can also add a preloader image
},
success: function (data) {
if (data) {
if (data.length < 100) {
button.children().remove(); // if last page, remove the button
noMoreAjax = true
return false
}
button.html('<a>Mutass többet</a>').before(data); // insert new posts
misha_loadmore_params.current_page++;
button.trigger("moreload-finish")
console.log("loading:", data.length)
// you can also fire the "post-load" event here if you use a plugin that requires it
// $( document.body ).trigger( 'post-load' );
} else {
button.children().remove(); // if no data, remove the button as well
noMoreAjax = true
console.log("no data")
}
}
});
}
/* ------------------------- Click on small articles ------------------------ */
$('article.home-small').click(function () {
let href = $(this).children('a.thumbnailwrapper').attr("href")
window.open(href, "_self")
})
/* ------------------------------ hover on home ----------------------------- */
//hover on big articles
$(".home-big h2 a").hover(function () {
let cc = $(this)
let cArticle = cc.parents("article")
let cMetadata = cArticle.children(".metadata")
//add hovered class
cArticle.addClass("hovered")
//add tag to header for bg
let artClasses = cArticle.attr("class").split(" ")
let theTag = findClassByStart(artClasses, "tag")
$("body, .header-1, .header-2").addClass("hover-" + theTag)
//transparent metadata
cMetadata.children(".categories, .postedon").addClass("transparent")
//animate border
cMetadata.stop().animate({ height: "25rem" }, 400, _ => {
//hide metadata
cMetadata.children(".categories, .postedon").hide().removeClass("transparent")
cMetadata.children(".alcim, .bevezeto").show().removeClass("transparent")
})
}, function () {
let cc = $(this)
let cArticle = cc.parents("article")
let cMetadata = cArticle.children(".metadata")
//remove hovered class
cArticle.removeClass("hovered")
//remove tag from header and body
let headerClasses = $(".header-1").attr("class").split(" ")
var hoverClass = findClassByStart(headerClasses, "hover")
$("body, .header-1, .header-2").removeClass(hoverClass)
//transparent metadata
cMetadata.children(".alcim, .bevezeto").addClass("transparent")
//animate height change
cMetadata.stop().animate({ height: "10rem" }, 400, _ => {
//hide and show metadata
cMetadata.children(".alcim, .bevezeto").hide().removeClass("transparent")
cMetadata.children(".categories, .postedon").removeClass("transparent").show()
})
})
/**
* finds a name of a class, from the first element
* @param {Array} classlist the list of classes to search from as an array
* @param {String} startString the string to search for
* @param {String} sep the separator that separates the startString from the rest of the classname
*/
function findClassByStart(classlist, startString, sep = "-") {
var fullstring
for (let i = 0; i < classlist.length; i++) {
let curr = classlist[i].split(sep)
if (curr[0] == startString) {
fullstring = classlist[i]
}
}
return fullstring
}
//hover on small articles
function showTitle(th) {
$(th).children("h2").show()
$(th).children(".metadata").addClass("vis")
}
function hideTitle(th) {
$(th).children("h2").hide()
$(th).children(".metadata").removeClass("vis")
}
$(document).on({
mouseenter: function () {
if (!Modernizr.touchevents) {
showTitle(this)
}
},
mouseleave: function () {
if (!Modernizr.touchevents) {
hideTitle(this)
}
}
}, '.home-small');
//touch on small articles
$(document).on({
'touchend': function (e) {
e.preventDefault()
var art = $(this).parents("article")
var metadata = art.children(".metadata")
if (metadata.hasClass("vis")) {
hideTitle(art)
} else {
hideTitle($(".vis").parents("article"))
showTitle(art)
}
}
}, ".home-small a.thumbnailwrapper")
/* -------------------------------------------------------------------------- */
/* EVENTS - ESEMÉNYEK */
/* -------------------------------------------------------------------------- */
if (isEsemeny) {
//add spaces to date
$(".event-metadata .ev-date").each(function () {
let repl = $(this).html().replace(/\.\b/g, ". ")
$(this).html(repl)
})
}
/* -------------------------------------------------------------------------- */
/* CIRCULAR TEXT */
/* -------------------------------------------------------------------------- */
const bedoListItems = ".wrapper .header #tag-nav ul li"
const bedoWords = bedoListItems + " a"
const bedoLetters = bedoWords + " span"
//move subs to wrapper
$(bedoListItems).each(function () {
let itemId = $(this).attr("id")
let tagClass = $(this).attr("class").split(" ")
let itemClass = findClassByStart(tagClass, 'tag')
// add wrapper div
// $(".sub-wrapper").append('<div id="' + itemId + '" class="bedo-sub-wrapper ' + itemClass + '"></div>')
// add tag title
// $(this).children("a").clone().appendTo(".sub-wrapper #" + itemId)
//add sub text
// $(this).children("span").appendTo(".sub-wrapper #" + itemId)
//add circle
// $(".sub-wrapper #" + itemId + " span").append('<div class="circle">')
})
//wrap each letter to spans
var charnum = 0
$(bedoWords).each(function () {
let chars = $(this).html().length + 1
$(this).lettering()
$(this).children("span").each(function () {
let origClass = $(this).attr("class")
let origClassNum = parseInt(origClass.split("r")[1])
let newClassNum = origClassNum + charnum
$(this).removeClass(origClass).addClass("char" + newClassNum)
})
charnum += chars
})
/* ---------------------------------- hover --------------------------------- */
$(bedoWords).hover(function () {
$(bedoLetters).addClass("pause")
$(this).children("span").addClass("current")
let currTagClass = $(this).parent().attr("class").split(" ")
let tagClass = findClassByStart(currTagClass, "tag")
console.log(".bedo-sub-wrapper ." + tagClass)
$(".sub-wrapper>.opened").removeClass("opened")
$(".sub-wrapper>." + tagClass).addClass("opened")
}, function () {
$(bedoLetters).removeClass("pause")
$(this).children("span").removeClass("current")
$(".sub-wrapper>.opened").removeClass("opened")
})
/* -------------------------------------------------------------------------- */
/* SINGLE */
/* -------------------------------------------------------------------------- */
if (isSingle) {
/* ----------------------------- images, gallery ---------------------------- */
//hide caption on desktop
if (!isMobile) {
$('.wp-block-gallery img, .wp-block-image img').hover(function () {
$(this).parent('a').next("figcaption").addClass("vis")
}, function () {
$('.wp-block-gallery .vis, .wp-block-image .vis')
.removeClass("vis")
})
}
/* -------------------------------- Lightbox -------------------------------- */
//group gallery images:
$('.wp-block-gallery a, .wp-block-image a').addClass('cb-gallery')
//copy figcaption to title
$("a.cb-gallery ~ figcaption").each(function () {
let captiotext = $(this).html()
$(this).prev('.cb-gallery').attr({ title: captiotext })
})
//http://www.jacklmoore.com/colorbox/
const colorboxSettings = {
transition: 'fade',
rel: 'cb-ballery',
maxWidth: '90%',
maxHeight: '80%',
trapFocus: false,
scrolling: false,
fixed: true,
previous: '',
next: '',
close: '',
}
// lightbox for galleries
$(".wp-block-gallery a").colorbox(colorboxSettings)
//single images
$(".wp-block-image a").colorbox(colorboxSettings)
/* ---------------------------- hover and click on related ---------------------------- */
$(document).on({
mouseenter: function () {
if (!Modernizr.touchevents) {
showTitle(this)
}
},
mouseleave: function () {
if (!Modernizr.touchevents) {
hideTitle(this)
}
}
}, '#related_posts li');
//touch on small articles
$(document).on({
'touchend': function (e) {
e.preventDefault()
var art = $(this).parents("li")
var metadata = art.children(".metadata")
if (metadata.hasClass("vis")) {
hideTitle(art)
} else {
hideTitle($(".vis").parents("li"))
showTitle(art)
}
}
}, "#related_posts li a.related_thumbnailwrapper")
//click on related
$('#related_posts li').click(function () {
let href = $(this).children('a.related_thumbnailwrapper').attr("href")
window.open(href, "_self")
})
/* ----------------------------- scroll to title ---------------------------- */
if (!isMobile) {
const titleWrapperHeight = $('article>.titlewrapper')[0].getBoundingClientRect().height
if ($('html, body').scrollTop() == 0) {
$('html, body').stop().animate({ scrollTop: titleWrapperHeight }, 400);
}
}
}//if single end
/* ------------------------------- END OF FILE ------------------------------ */
});
})(jQuery, this);