How could I add the following to my mediawiki main page? - javascript

I would like to add this timeline gimmick https://codepen.io/alvarotrigo/pen/yLzBJaN to the main page in my medawiki. How might I go about importing it? I have a script that enables HTML, but I do not know how to enable the CSS or JS.
I am not really a programmer and just trying to figure out the best way to test this out.
here is the code:
`
(function ($) {
$(function () {
$(window).on('scroll', function () {
fnOnScroll();
});
$(window).on('resize', function () {
fnOnResize();
});
var agTimeline = $('.js-timeline'),
agTimelineLine = $('.js-timeline_line'),
agTimelineLineProgress = $('.js-timeline_line-progress'),
agTimelinePoint = $('.js-timeline-card_point-box'),
agTimelineItem = $('.js-timeline_item'),
agOuterHeight = $(window).outerHeight(),
agHeight = $(window).height(),
f = -1,
agFlag = false;
function fnOnScroll() {
agPosY = $(window).scrollTop();
fnUpdateFrame();
}
function fnOnResize() {
agPosY = $(window).scrollTop();
agHeight = $(window).height();
fnUpdateFrame();
}
function fnUpdateWindow() {
agFlag = false;
agTimelineLine.css({
top: agTimelineItem.first().find(agTimelinePoint).offset().top - agTimelineItem.first().offset().top,
bottom: agTimeline.offset().top + agTimeline.outerHeight() - agTimelineItem.last().find(agTimelinePoint).offset().top
});
f !== agPosY && (f = agPosY, agHeight, fnUpdateProgress());
}
function fnUpdateProgress() {
var agTop = agTimelineItem.last().find(agTimelinePoint).offset().top;
i = agTop + agPosY - $(window).scrollTop();
a = agTimelineLineProgress.offset().top + agPosY - $(window).scrollTop();
n = agPosY - a + agOuterHeight / 2;
i <= agPosY + agOuterHeight / 2 && (n = i - a);
agTimelineLineProgress.css({height: n + "px"});
agTimelineItem.each(function () {
var agTop = $(this).find(agTimelinePoint).offset().top;
(agTop + agPosY - $(window).scrollTop()) < agPosY + .5 * agOuterHeight ? $(this).addClass('js-ag-active') : $(this).removeClass('js-ag-active');
})
}
function fnUpdateFrame() {
agFlag || requestAnimationFrame(fnUpdateWindow);
agFlag = true;
}
});
})(jQuery);
`

Related

Universal script for moving elements in DOM

I want to create a universal code for easy moving elements in DOM between desktop and mobile. It's not my idea as well as not my code. It was for Prestashop 1.7 only, but I want to change it for any project.
The idea is that you can wrap some code you want to move in an absolute different place on mobile with <div id="_desktop_some-block">Some content</div>, and place empty <div id="_mobile_some-block"></div> where you want to see it on mobile devices and when window reach (for ex.) 768px the HTML of the element will be moving to another one.
So here is an original code:
import $ from 'jquery';
import prestashop from 'prestashop';
prestashop.responsive = prestashop.responsive || {};
prestashop.responsive.current_width = window.innerWidth;
prestashop.responsive.min_width = 768;
prestashop.responsive.mobile = prestashop.responsive.current_width < prestashop.responsive.min_width;
function swapChildren(obj1, obj2)
{
var temp = obj2.children().detach();
obj2.empty().append(obj1.children().detach());
obj1.append(temp);
}
function toggleMobileStyles()
{
if (prestashop.responsive.mobile) {
$("*[id^='_desktop_']").each(function(idx, el) {
var target = $('#' + el.id.replace('_desktop_', '_mobile_'));
if (target.length) {
swapChildren($(el), target);
}
});
} else {
$("*[id^='_mobile_']").each(function(idx, el) {
var target = $('#' + el.id.replace('_mobile_', '_desktop_'));
if (target.length) {
swapChildren($(el), target);
}
});
}
prestashop.emit('responsive update', {
mobile: prestashop.responsive.mobile
});
}
$(window).on('resize', function() {
var _cw = prestashop.responsive.current_width;
var _mw = prestashop.responsive.min_width;
var _w = window.innerWidth;
var _toggle = (_cw >= _mw && _w < _mw) || (_cw < _mw && _w >= _mw);
prestashop.responsive.current_width = _w;
prestashop.responsive.mobile = prestashop.responsive.current_width < prestashop.responsive.min_width;
if (_toggle) {
toggleMobileStyles();
}
});
$(document).ready(function() {
if (prestashop.responsive.mobile) {
toggleMobileStyles();
}
});
Here is what I'm trying to do:
var windowWidth = $(window).innerWidth();
var windowMinWidth = 768;
var windowResponsiveMobile = windowWidth < windowMinWidth;
function swapChildren(obj1, obj2)
{
var temp = obj2.children().detach();
obj2.empty().append(obj1.children().detach());
obj1.append(temp);
}
function toggleMobileStyles()
{
if (windowResponsiveMobile) {
$("*[id^='_desktop_']").each(function(idx, el) {
var target = $('#' + el.replace('_desktop_', '_mobile_'));
if (target.length) {
swapChildren($(el), target);
}
});
} else {
$("*[id^='_mobile_']").each(function(idx, el) {
var target = $('#' + el.replace('_mobile_', '_desktop_'));
if (target.length) {
swapChildren($(el), target);
}
});
}
}
$(window).on('resize', function() {
var _cw = windowWidth;
var _mw = windowMinWidth;
var _w = $(window).innerWidth();
var _toggle = (_cw >= _mw && _w < _mw) || (_cw < _mw && _w >= _mw);
windowWidth = _w;
windowResponsiveMobile = windowWidth < windowMinWidth;
if (_toggle) {
toggleMobileStyles();
}
});
$(document).ready(function() {
if (windowResponsiveMobile) {
toggleMobileStyles();
}
});
Currently it doesn't work, but I don't see any errors in the console and it little bit confuse...
Please help me to finish it so it could work.
var windowWidth = $(window).innerWidth();
var windowMinWidth = 768;
var windowResponsiveMobile = windowWidth < windowMinWidth;
function swapChildren(obj1, obj2)
{
var temp = obj2.children().detach();
obj2.empty().append(obj1.children().detach());
obj1.append(temp);
}
function toggleMobileStyles()
{
if (windowResponsiveMobile) {
$("[id^='_desktop_']").each(function(idx, el) {
var target = $('#' + el.id.replace('_desktop_', '_mobile_'));
if (target.length) {
swapChildren($(el), target);
}
});
} else {
$("[id^='_mobile_']").each(function(idx, el) {
var target = $('#' + el.id.replace('_mobile_', '_desktop_'));
if (target.length) {
swapChildren($(el), target);
}
});
}
}
$(window).on('resize', function() {
var _cw = windowWidth;
var _mw = windowMinWidth;
var _w = $(window).innerWidth();
var _toggle = (_cw >= _mw && _w < _mw) || (_cw < _mw && _w >= _mw);
windowWidth = _w;
windowResponsiveMobile = windowWidth < windowMinWidth;
if (_toggle) {
toggleMobileStyles();
}
});
$(document).ready(function() {
if (windowResponsiveMobile) {
toggleMobileStyles();
}
});
Here is the updated code, you just removed the id in the target selector.

How to get my function to increase variable "_time"

// videogame.js
// don't forget to validate at jslint.com
/*jslint devel: true, browser: true */
/*global $*/
$(function () {
"use strict";
// global functions
function boundaryCheck(element_selector) {
var element = $(element_selector);
var universe = $("#universe");
var p = element.position();
if (p.left < 0) {
element.css("left", "0px");
}
if (p.top < 0) {
element.css("top", "0px");
}
if (p.left + element.width() > universe.width()) {
element.css("left", (universe.width() - element.width()) + "px");
}
if (p.top + element.height() > universe.height()) {
element.css("top", (universe.height() - element.height()) + "px");
}
}
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
// Constructor for Player Ship object
function PlayerShip() {
var my = {};
$("#universe").append($("<div>").attr("id", "player"));
my.navigate = function (keys) {
var RIGHTARROW_KEYCODE = 39;
var LEFTARROW_KEYCODE = 37;
var UPARROW_KEYCODE = 38;
var DOWNARROW_KEYCODE = 40;
if (keys === RIGHTARROW_KEYCODE) {
$("#player").css("left", "+=10px");
}
if (keys === LEFTARROW_KEYCODE) {
$("#player").css("left", "-=10px");
}
if (keys === UPARROW_KEYCODE) {
$("#player").css("top", "-=10px");
}
if (keys === DOWNARROW_KEYCODE) {
$("#player").css("top", "+=10px");
}
boundaryCheck("#player");
};
return my;
}
// Constructor for Enemy Ship object
function EnemyShip() {
var my = {};
$("#universe").append($("<div>").attr("id", "enemy"));
my.move = function (paused) {
if (!paused) {
var left = Boolean(getRandomInt(0, 2));
var top = Boolean(getRandomInt(0, 2));
if (left) {
$("#enemy").css("left", "-=" + getRandomInt(1, 10) + "px");
} else {
$("#enemy").css("left", "+=" + getRandomInt(1, 10) + "px");
}
if (top) {
$("#enemy").css("top", "-=" + getRandomInt(1, 10) + "px");
} else {
$("#enemy").css("top", "+=" + getRandomInt(1, 10) + "px");
}
boundaryCheck("#enemy");
}
};
return my;
}
// this might make an asteroid happen, maybe. I don't know if it will work.
function Asteroid() {
var my = {};
$("#universe").append($("<div>").attr("id", "asteroid"));
my.move = function (paused) {
if (!paused) {
var left = Boolean(getRandomInt(0, 2));
var top = Boolean(getRandomInt(0, 2));
if (left) {
$("#asteroid").css("left", "-=" + getRandomInt(1, 10) + "px");
} else {
$("#asteroid").css("left", "+=" + getRandomInt(1, 10) + "px");
}
if (top) {
$("#asteroid").css("top", "-=" + getRandomInt(1, 10) + "px");
} else {
$("#asteroid").css("top", "+=" + getRandomInt(1, 10) + "px");
}
boundaryCheck("#asteroid");
}
};
return my;
}
// Constructor for Game object
function Game() {
// total points
var _health = 1000;
var _time = 0;
// is the game paused?
var _game_paused = false;
// speed of background animation in ms (larger = slower)
var _background_speed = 100;
// player ship
var _player_ship = new PlayerShip();
// enemy ship
var _enemy_ship = new EnemyShip();
var _asteroid = new Asteroid(); //make this an actual thing
var my = {
health: _health,
time: _time,
game_paused: _game_paused,
background_speed: _background_speed,
player_ship: _player_ship,
enemy_ship: _enemy_ship,
asteroid: _asteroid
};
$("#universe").append($("<div>").attr("id", "results"));
$("#results").append($("<h1>"));
$("#universe").append($("<div>").attr("id", "results2"));
$("#results2").append($("<h1>"));
my.health = function (value) {
if (value === undefined) {
return _health;
}
_health = value;
return my;
};
my.time = function (value) {
if (value === undefined) {
return _time;
}
_time = value;
return my;
};
my.game_paused = function (value) {
if (value === undefined) {
return _game_paused;
}
_game_paused = value;
return my;
};
my.background_speed = function (value) {
if (value === undefined) {
return _background_speed;
}
_background_speed = value;
return my;
};
my.player_ship = function (value) {
if (value === undefined) {
return _player_ship;
}
_player_ship = value;
return my;
};
function runtimer() {
_time++;
};
my.enemy_ship = function (value) {
if (value === undefined) {
return _enemy_ship;
}
_enemy_ship = value;
return my;
};
my.asteroid = function (value) {
if (value === undefined) {
return _asteroid;
}
_asteroid = value;
return my;
};
// METHODS
// display total points
my.displayHealth = function () {
$("#results h1").html("Health: " + _health);
};
my.increaseTime = function () {
setInterval(function(){ runTimer() }, 1000)
}
my.displayTimer = function () {
$("#results2 h1").html("Time: "+ _time);
};
my.moveBackground = function () {
if (!_game_paused) {
var background_position = $("#universe")
.css("backgroundPosition")
.split(" ");
var current_x = parseInt(background_position[0], 10);
var current_y = parseInt(background_position[1], 10);
var new_x = current_x - 1;
var new_y = current_y;
$("#universe").css({
"background-position": new_x + "px " + new_y + "px"
});
}
};
my.checkKeys = function () {
var ESCAPE_KEYCODE = 27;
$(document).keydown(function (key_event) {
if (key_event.which === ESCAPE_KEYCODE) {
if (_game_paused) {
_game_paused = false;
$("#pause").remove();
} else {
_game_paused = true;
var pause = $("<div>", {id: "pause"});
$("body").prepend(pause);
}
} else {
_player_ship.navigate(key_event.which);
}
});
};
my.checkCollisions = function (paused) {
var p = $("#player");
var e = $("#enemy");
var ppos = p.position();
var epos = e.position();
if (!paused) {
if (
(
(ppos.left + p.width() < epos.left) ||
(ppos.left > epos.left + e.width())
) ||
(
(ppos.top + p.height() < epos.top) ||
(ppos.top > epos.top + e.height())
)
) {
return false;
} else {
return true;
}
}
};
my.checkAsteroid = function (paused) {
var p = $("#player");
var a = $("#asteroid");
var ppos = p.position();
var apos = a.position();
if (!paused) {
if (
(
(ppos.left + p.width() < apos.left) ||
(ppos.left > apos.left + a.width())
) ||
(
(ppos.top + p.height() < apos.top) ||
(ppos.top > apos.top + a.height())
)
) {
return false;
} else {
return true;
}
}
};
my.play = function () {
_enemy_ship.move(_game_paused);
_asteroid.move(_game_paused);
if (my.checkCollisions(_game_paused)) {
_health --;
my.displayHealth();
} else if (
my.checkAsteroid(_game_paused)) {
_health --;
my.displayHealth();
}
};
return my;
}
var game = new Game();
game.checkKeys();
game.displayHealth();
game.displayTimer();
game.increaseTime();
setInterval(game.moveBackground, game.background_speed);
setInterval(game.play, game.background_speed);
});
I'm relatively new to programming. I took a class in high school, which was very mediocre. I'm now taking some starter courses in college, and my assignment is to improve a generic space game (which I have already started doing). I have a div for the timer, but for some reason, I can't get any functions to increase the _time variable. It's almost as though they're not allowed to access it. I have a function called "runTimer", which is supposed to increase "_time" by one every time it is run. I have another function called "increaseTime", which is supposed to run "runTimer" every 1000 milliseconds. The variable never seems to increase though. This hasn't been my first spaghetti code implementation of a timer, since I've tried various things over the past few hours. I just can't understand why the variable won't increase.
This is a big hunk of code. As RobG pointed out, try to work on paring back your question to the minimal, complete, and verifiable example you can.
That said, at a glance, it would appear that your timer probably is updating. At least _time is.
The problem is likely you are never re-drawing your div, so it isn't showing the updated value. You need to call game.displayTimer() every time _time updates.
Probably the easiest place to add it would be in your setInterval() in increaseTime():
my.increaseTime = function () {
setInterval(function(){
runTimer();
my.displayTime();
}, 1000)
}

How to get a variable into a function from another under "use strict"

I really don't know how to get the following variable from a function into another function. I've read most of the articles and answers about that, and I think my example is more complex. Otherwise, I'm doing it wrong.
This is the function I'm using to determine the value of the wpbar variable. I even could start with $(document).ready(function(), but I removed it for the example:
function wp_adminbar() {
"use strict";
var win = $(window),
wpbar = 0;
if ($('body').hasClass('admin-bar')) {
win.on("resize load",function(){
var wpbar, w = window,
d = document,
e = d.documentElement,
g = d.getElementsByTagName('body')[0],
x = w.innerWidth || e.clientWidth || g.clientWidth;
if (x <= 782) {
wpbar = 46;
} else if (x > 782) {
wpbar = 32;
}
});
}
return wpbar;
}
I want to use the variable wpbar into this another function:
$(document).ready(function($) {
"use strict";
var wpbar = wp_adminbar();
console.log(wpbar); // Returns: 0
});
I'm stuck in that. Edit: Actually, return wpbar; is not working at all.
Edit: Full code of a function contaning the first function. In this case, it works:
$(document).ready(function($) {
"use strict";
var win = $(window),
nav_fixed = $('.enable-fixed'),
header = $('#header-v1');
if (!nav_fixed.length || !header.length) return;
// WordPress Toolbar
var wpbar = 0;
if ($('body').hasClass('admin-bar')) {
win.on("resize load",function(){
var w = window,
d = document,
e = d.documentElement,
g = d.getElementsByTagName('body')[0],
x = w.innerWidth || e.clientWidth || g.clientWidth;
if (x <= 782) {
wpbar = 46;
} else if (x > 782) {
wpbar = 32;
}
});
}
var max_h = 89,
min_h = 55,
var_h = max_h - min_h,
menu = $('.sticky-wrapper-v1, #header-v1, #header-v1 .wrap, #header-v1 .menuwrap ul:first-child > li > a, #header-v1 .main-nav-search a'),
logo = $('#header-v1 #logo, #header-v1 #logo img'),
nav = $('#navigation'),
set_height = function(){
var st = win.scrollTop() + wpbar,
new_h = 0,
new_p = 0,
wrapper = $('.sticky-wrapper-v1'),
top_p = wrapper.offset().top;
if (st <= top_p) {
new_h = max_h;
new_p = 0;
} else if (st <= (top_p + var_h)) {
new_h = max_h - st + top_p;
new_p = st - top_p;
header.removeClass("header-scrolled");
} else {
new_h = min_h;
new_p = var_h;
header.addClass("header-scrolled");
}
wrapper.css('margin-bottom', new_p);
menu.css({'height': new_h + 'px', 'lineHeight': new_h + 'px'});
logo.css({'maxHeight': new_h + 'px'});
nav.css({'height': new_h + 'px'});
};
win.one("resize",function(){
$(".navbtn").toggle(function() {
set_height;
}, function () {
set_height;
});
set_height;
});
win.on('debouncedresize', function(){
max_h = $(menu).attr('style',"").filter(':first').height();
set_height();
});
win.on('scroll', function(){
window.requestAnimationFrame( set_height );
});
set_height();
});

Changing windows width with JQuery without reloading the page again

I have a JQuery rotator in my website with a slides images and I want to make the website responsive. I'm using CSS media queries to do it. I want to change the slide width (which defines in JS) when the windows width is less than 800px.
So long, I did something like this:
var responsiveSlideWidth;
if ($(window).width() < 800) {
responsiveSlideWidth = 700;
}
else {
responsiveSlideWidth = 960;
}
var defaults = {
container: '.rotatorWrapper',
animationduration: 1000,
slideWidth: responsiveSlideWidth
};
The problem is that it is working just after page reload. Thats means: if I resize the window size its is not working until I reload the page.
Any suggestions?
Thanks.
EDIT: My full code:
(function ($) {
$.fn.Rotator = function (options) {
var responsiveSlideWidth;
if ($(window).width() < 800) {
responsiveSlideWidth = 700;
}
else {
responsiveSlideWidth = 960;
}
var defaults = {
container: '.rotatorWrapper',
animationduration: 1000,
slideWidth: responsiveSlideWidth
};
options = $.extend(defaults, options);
elm = this;
var pageIndex = 0,
slideCount = 0;
var _init = function () {
slideCount = elm.find(options.container).children().children().length;
elm.find(options.container).children().width(slideCount * options.slideWidth);
_bindEvents();
_togglePager();
};
var _bindEvents = function () {
var jElm = $(elm);
jElm.find('.prev').on('click', _previous);
jElm.find('.next').on('click', _next);
};
var _next = function (e) {
e.preventDefault();
if (pageIndex >= 0 && pageIndex < slideCount - 1) {
pageIndex++;
elm.find(options.container).children().animate({
left: "-=" + options.slideWidth
}, options.animationduration);
}
_togglePager();
};
var _previous = function (e) {
e.preventDefault();
if (pageIndex <= slideCount) {
pageIndex--;
elm.find(options.container).children().animate({
left: "+=" + options.slideWidth
}, options.animationduration);
}
_togglePager();
};
var _togglePager = function () {
var $elm = $(elm);
var prev = $elm.find('.prev');
var next = $elm.find('.next');
console.log('slide count' + pageIndex + ' Page Index' + pageIndex)
if (pageIndex >= slideCount - 1) {
next.hide();
} else {
next.show();
}
if (pageIndex <= 0) {
prev.hide();
} else {
prev.show();
}
}
return _init(elm);
}
})(jQuery);

Javascript replay user input

I'm trying to capture user input (jquery event objects) in a captured array. I am tacking a t property on to the event, which is each event's elapsed time from the start of recording. Then I want to walk back through that array, using a setTimeout within a closure in a for loop in order to trigger those events with the same timing as user input.
I just don't understand why the animations won't play on the way back... !??!
Please, if anyone has insight into this... HELP!
$(function() {
var dancer = document.getElementById('dancer');
var $dancer = $(dancer);
var dancerContainer = document.querySelector('.dancer-container');
var $dancerContainer = $(dancerContainer);
var count = 3;
var captured = [];
var countInterval;
function replayDance(captured) {
for (i = 0; i < captured.length; i++) {
e = captured[i];
t = e.t;
setTimeout((function (e) {
return function () {
// $dancer.trigger(e.type);
// this should be
$dancer.trigger(e.originalEvent);
};
})(e), t);
}
}
function countdown() {
console.log(count);
--count;
if (count == 0) {
console.log('recording')
captureInput();
clearInterval(countInterval);
count = 3;
}
}
function captureInput() {
var mouseCapture = [];
var keyCapture = [];
var start = new Date().getTime();
$(document).on('mousemove.capture', function(event) {
event.t = new Date().getTime() - start;
captured.push(event);
});
$(document).on('keyup.capture', function(event) {
event.t = new Date().getTime() - start;
captured.push(event);
});
setTimeout(function() {
console.log('finished capturing');
$(document).off('.capture');
}, 3000);
}
function followMouse(event) {
var width = $(window).width();
var height = $(window).height();
var mouseX = event.pageX - (width * 0.25);
var mouseY = event.pageY - (height * 0.25);
var angleX = (mouseY / height) * 45;
var angleY = (mouseX / width) * 45;
dancer.style.webkitTransform = "rotateX(" + angleX + "deg) rotateY(" + angleY + "deg)";
console.log(dancer.style.webkitTransform);
}
function resize() {
var y = ($(window).height() - 250) * 0.5;
$("#box").css('margin-top', y + 'px');
}
function triggerAnimation(el, klassName) {
el.stop(true, false).addClass(klassName).one('webkitAnimationEnd', function() { el.removeClass(klassName) });
}
$(document).on('keyup', function(event) {
switch (event.which) {
case 49:
triggerAnimation($dancerContainer, 'shake');
break;
case 50:
triggerAnimation($dancerContainer, 'bounce');
break;
case 51:
triggerAnimation($dancerContainer, 'swing');
break;
case 52:
triggerAnimation($dancerContainer, 'wobble');
break;
}
});
$('#button-record').on('click', function(e) {
countInterval = setInterval(countdown, 1000);
});
$('#button-replay').on('click', function(e) {
if (captured.length) {
replayDance(captured);
} else {
console.log('nothing captured!');
}
})
$(window).on('resize', resize);
$(document).ready(resize);
$(document).on('mousemove', followMouse);
});
I needed to trigger the originalEvent attached to the Event object, rather than trying to trigger the e.type again. Corrected the offending line of code in my post.

Categories

Resources