loading external library in riotjs - javascript

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

Related

Adding data in node of jstree through dropdown not working properly

I am trying to add a dropdown in a node and want to be able to create and remove the nodes. I am able to do that but whenever i create/remove a node the dropdown values that i have selected are removed from where the node is created or removed. I am using select2 for dropdown if that helps.
below is the link for demonstration
https://www.arsallodhi.com/jstree/index.html
thanks in advance
I think redraw method is called which does removes the values. So i tried to catch it but couldnt.
<html>
<head>
<style>
.jstree-default .jstree-node, .jstree-leaf {
min-height: 35px !important;
}
.jstree-open .jstree-node {
padding-top: 15px !important;
}
</style>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/css/select2.min.css" rel="stylesheet"/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css"/>
</head>
<body>
<div id="jstreee">
<ul>
<li class="jstree-open">
Organization
</li>
</ul>
</div>
<script src="https://kendo.cdn.telerik.com/2019.2.514/js/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/js/select2.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>
<script>
function formatDropdown1(option) {
if (option.id) {
return option.text;
} else {
return '';
}
};
function addTagValueClass() {
$('.tag').select2({
placeholder: '',
allowClear: true,
tags: true,
templateSelection: formatDropdown1,
});
}
var counter = 0;
function customMenu2(node) {
var position = 'inside';
var parent;
var selected_id;
selected_id = parent = $('#jstreee').jstree('get_selected');
counter++;
var node_data;
node_data = "<li class='node-li'><select data-live-search='true' class='tag' placeholder='Tag'><option></option><option value='volvo'>Project</option><option value='saab'>Owner</option><option value='mercede'>Department</option><option value='audi'>Business Unit</option></select></li>"
var items = {
createItem: {
label: "Add Node",
action: function () {
$('#jstreee').jstree().create_node(parent, {"id": "ajson5" + counter, "text": node_data}, position
, function () {
addTagValueClass();
$('#jstreee').jstree().open_node('#' + parent);
});
}
},
deleteItem: {
label: "Remove Node",
action: function () {
if (selected_id != "j1_1") {
$('#jstreee').jstree().delete_node(selected_id);
addTagValueClass();
}
}
}
};
return items;
}
$('#jstreee').on('open_node.jstree', function (e, data) {
addTagValueClass();
});
$('#jstreee').jstree({
"core": {"check_callback": true, "themes": {"icons": false}, "toggle_node": true}, // so that modifying operations work
"plugins": ["contextmenu"], contextmenu: {items: customMenu2}
});
</script>
</body>
</html>
I want that the values which i have set through the dropdown remain even when a node is created or removed.

smoothstate stops other javascript from running (electron)

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()
}
}
})()
}

href '#'? Trying to make audio controls

var tracklist = [{
src: 'https://primi.gg/assets/audio/gucci.mp3',
cover: 'https://i.imgur.com/Vayupax.jpg'
},
{
src: 'https://primi.gg/assets/audio/anarchyacres.mp3',
cover: 'https://i.imgur.com/Vayupax.jpg'
},
{
src: 'https://primi.gg/assets/audio/sempiternal.mp3',
cover: 'https://i.imgur.com/Vayupax.jpg'
},
{
src: 'https://primi.gg/assets/audio/wither.mp3',
cover: 'https://i.imgur.com/Vayupax.jpg'
},
{
src: 'https://primi.gg/assets/audio/enemy.mp3',
cover: 'https://i.imgur.com/Vayupax.jpg'
},
{
src: 'https://primi.gg/assets/audio/antisocial.mp3',
cover: 'https://i.imgur.com/Vayupax.jpg'
},
];
var player = false;
var track = 1;
var lastTrack = -1;
var play = function() {
if (lastTrack != track) {
player.src = tracklist[track - 1].src;
}
lastTrack = track;
if (player.paused) {
player.play();
}
};
$(document).ready(function() {
player = document.createElement('audio');
$('a.player-control').click(function(event) {
event.preventDefault();
});
$('#play').click(function() {
play();
});
$('#pause').click(function() {
if (!player.paused) {
player.pause();
}
});
$('#next').click(function() {
track++;
if (track > tracklist.length) {
track = 1;
}
play();
});
$('#prev').click(function() {
track--;
if (track < 1) {
track = tracklist.length;
}
play();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
prev
play
pause
forward
I'm basically trying to make a custom audio control with css and html, but put everything in place it doesn't work. I think it has something to do with the specific part of code "href='#'... I'm entirely new to coding so any help and pointers would be nice! Here is the entire code and thank you in advance!
The JS
Your javascript code is saved as a .css file, you need to save it as .js and import it into your html using <script></script> tags. You will also need to use the jquery library. Place this in the head section before your script, e.g.
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https:/yourscript.js"></script>
Best of luck

ReferenceError: jQuery is not defined in main.js file

I am running into this error all of a sudden. I haven't anything with the Javascript or jQuery code so not sure why I'm getting this error all of a sudden.
This is the error I'm getting when trying to run my code:
Debugger listening on [::]:15454
/home/ubuntu/workspace/assets/js/main.js:232
}(jQuery);
^
ReferenceError: jQuery is not defined
Code:
(function($) {
skel.breakpoints({
xxlarge: '(max-width: 1920px)',
xlarge: '(max-width: 1680px)',
large: '(max-width: 1280px)',
medium: '(max-width: 1000px)',
small: '(max-width: 736px)',
xsmall: '(max-width: 480px)',
});
$(function() {
var $window = $(window),
$body = $('body'),
$header = $('#header'),
$all = $body.add($header);
// Disable animations/transitions until the page has loaded.
$body.addClass('is-loading');
$window.on('load', function() {
window.setTimeout(function() {
$body.removeClass('is-loading');
}, 0);
});
// Touch mode.
skel.on('change', function() {
if (skel.vars.mobile || skel.breakpoint('small').active)
$body.addClass('is-touch');
else
$body.removeClass('is-touch');
});
// Fix: Placeholder polyfill.
$('form').placeholder();
// Fix: IE flexbox fix.
if (skel.vars.IEVersion <= 11
&& skel.vars.IEVersion >= 10) {
var $main = $('.main.fullscreen'),
IEResizeTimeout;
$window
.on('resize.ie-flexbox-fix', function() {
clearTimeout(IEResizeTimeout);
IEResizeTimeout = setTimeout(function() {
var wh = $window.height();
$main.each(function() {
var $this = $(this);
$this.css('height', '');
if ($this.height() <= wh)
$this.css('height', (wh - 50) + 'px');
});
});
})
.triggerHandler('resize.ie-flexbox-fix');
}
// Prioritize "important" elements on small.
skel.on('+small -small', function() {
$.prioritize(
'.important\\28 small\\29',
skel.breakpoint('small').active
);
});
// Gallery.
$window.on('load', function() {
var $gallery = $('.gallery');
$gallery.poptrox({
baseZIndex: 10001,
useBodyOverflow: false,
usePopupEasyClose: false,
overlayColor: '#1f2328',
overlayOpacity: 0.65,
usePopupDefaultStyling: false,
usePopupCaption: true,
popupLoaderText: '',
windowMargin: 50,
usePopupNav: true
});
// Hack: Adjust margins when 'small' activates.
skel
.on('-small', function() {
$gallery.each(function() {
$(this)[0]._poptrox.windowMargin = 50;
});
})
.on('+small', function() {
$gallery.each(function() {
$(this)[0]._poptrox.windowMargin = 5;
});
});
});
// Section transitions.
if (skel.canUse('transition')) {
var on = function() {
// Galleries.
$('.gallery')
.scrollex({
top: '30vh',
bottom: '30vh',
delay: 50,
initialize: function() { $(this).addClass('inactive'); },
terminate: function() { $(this).removeClass('inactive'); },
enter: function() { $(this).removeClass('inactive'); },
leave: function() { $(this).addClass('inactive'); }
});
// Generic sections.
$('.main.style1')
.scrollex({
mode: 'middle',
delay: 100,
initialize: function() { $(this).addClass('inactive'); },
terminate: function() { $(this).removeClass('inactive'); },
enter: function() { $(this).removeClass('inactive'); },
leave: function() { $(this).addClass('inactive'); }
});
$('.main.style2')
.scrollex({
mode: 'middle',
delay: 100,
initialize: function() { $(this).addClass('inactive'); },
terminate: function() { $(this).removeClass('inactive'); },
enter: function() { $(this).removeClass('inactive'); },
leave: function() { $(this).addClass('inactive'); }
});
// Contact.
$('#contact')
.scrollex({
top: '50%',
delay: 50,
initialize: function() { $(this).addClass('inactive'); },
terminate: function() { $(this).removeClass('inactive'); },
enter: function() { $(this).removeClass('inactive'); },
leave: function() { $(this).addClass('inactive'); }
});
};
var off = function() {
// Galleries.
$('.gallery')
.unscrollex();
// Generic sections.
$('.main.style1')
.unscrollex();
$('.main.style2')
.unscrollex();
// Contact.
$('#contact')
.unscrollex();
};
skel.on('change', function() {
if (skel.breakpoint('small').active)
(off)();
else
(on)();
});
}
// Events.
var resizeTimeout, resizeScrollTimeout;
$window
.resize(function() {
// Disable animations/transitions.
$body.addClass('is-resizing');
window.clearTimeout(resizeTimeout);
resizeTimeout = window.setTimeout(function() {
// Update scrolly links.
$('a[href^="#"]').scrolly({
speed: 1500,
offset: $header.outerHeight() - 1
});
// Re-enable animations/transitions.
window.setTimeout(function() {
$body.removeClass('is-resizing');
$window.trigger('scroll');
}, 0);
}, 100);
})
.load(function() {
$window.trigger('resize');
});
});
})(jQuery);
Edit:
here is the code from bottom of index.html
</footer>
<!-- Scripts -->
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/jquery.poptrox.min.js"></script>
<script src="assets/js/jquery.scrolly.min.js"></script>
<script src="assets/js/jquery.scrollex.min.js"></script>
<script src="assets/js/skel.min.js"></script>
<script src="assets/js/util.js"></script>
<!--[if lte IE 8]><script src="assets/js/ie/respond.min.js"></script><![endif]-->
<script src="assets/js/main.js"></script>
</body>
</html>
here is the code from bottom of index.html
<!-- Scripts -->
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/jquery.poptrox.min.js"></script>
<script src="assets/js/jquery.scrolly.min.js"></script>
<script src="assets/js/jquery.scrollex.min.js"></script>
<script src="assets/js/skel.min.js"></script>
<script src="assets/js/util.js"></script>
<!--[if lte IE 8]><script src="assets/js/ie/respond.min.js"></script><![endif]-->
<script src="assets/js/main.js"></script>

Image preview script breaks on uploading the same image that was previously deleted

I am using this package, and I have modified it a bit, so that I can upload, drag and sort the images and preview them in the browser. Uploading works fine, and deleting of images. But I found a scenario when the script breaks. When I have more than one image and I delete the first image, on trying to upload the same image that I deleted the script doesn't work anymore. But if I don't try to upload the same image immediately and first upload some other and then the one that was deleted, then it works. Also, I don't get any errors in the console. I am not sure how to fix this.
My full code is here.
This is part of the code:
$(document).ready(function () {
var imageCounter = 0;
$('#articleForm').submit(function () {
uploadPosition();
});
function uploadPosition() {
var uploadedImagesPositions = [];
$.each($('.jFiler-item-thumb-image'), function (index, value) {
$(this).attr('data-position-index', index);
uploadedImagesPositions[index] = $(this).find('img').attr('src');
});
if (!$('input[name="uploadedItems"]').length) {
$('<input>', {
type: "hidden",
name: "uploadedItems"
}).appendTo('#articleForm')
}
$('input[name="uploadedItems"]').val(JSON.stringify(uploadedImagesPositions));
$("input[name^='jfiler-items-exclude-']:hidden").detach();
console.log(uploadedImagesPositions);
}
$('#upload').filer({
limit: null,
maxSize: null,
extensions: null,
changeInput: '<div class="jFiler-input-dragDrop"><h1>+</h1></div>',
showThumbs: true,
appendTo: '.uploaded_items',
theme: "default",
templates: {
box: '<div class="jFiler-item-list"></div>',
item: '<div class="jFiler-item img-container dragdiv"></div>',
itemAppend: '<div class="jFiler-item img-container dragdiv"></div>',
progressBar: '<div class="bar"></div>',
itemAppendToEnd: false,
removeConfirmation: false,
_selectors: {
list: '.jFiler-item-list',
item: '.jFiler-item',
progressBar: '.bar',
remove: '.jFiler-item-trash-action',
}
},
uploadFile: {
url: "/admin/articles/ajax",
data: {
'_token': $('input[name="_token"]').val()
},
type: 'POST',
enctype: 'multipart/form-data',
beforeSend: function () {},
success: function (data, el) {
uploadedImagesPositions = [];
console.log(data);
var filenameArray = data.split('/');
var name = filenameArray.slice(-1).pop();
var filename = name.replace(/[\/\s()]/g, '');
var imageContainer = $('[data-jfiler-index="' + imageCounter + '"]').first();
$('<div class="jFiler-item-thumb-image"><img src="/imagecache/thumb/' + filename + '"></div><div class="overlay"><span><i class="jFiler-item-trash-action ion-trash-a"></span></div>').appendTo(imageContainer);
imageCounter++;
$(".dragdiv").each(function () {
makeElementAsDragAndDrop($(this));
});
$('.images-refresh').hide();
$('.images-refresh').click(function () {
$(this).closest("form").submit()
});
function makeElementAsDragAndDrop(elem) {
$(elem).draggable({
revert: "invalid",
cursor: "move",
helper: "clone"
});
$(elem).droppable({
activeClass: "ui-state-hover",
hoverClass: "ui-state-active",
drop: function (event, ui) {
uploadedImagesPositions = [];
$('.images-form a').hide();
$('.images-refresh').show();
var $dragElem = $(ui.draggable).clone().replaceAll(this);
$(this).replaceAll(ui.draggable);
makeElementAsDragAndDrop(this);
makeElementAsDragAndDrop($dragElem);
}
});
}
var parent = el.find(".jFiler-jProgressBar").parent();
el.find(".jFiler-jProgressBar").fadeOut("slow", function () {
$("<div class=\"jFiler-item-others text-success\"><i class=\"icon-jfi-check-circle\"></i> Success</div>").hide().appendTo(parent).fadeIn("slow");
});
},
error: function (el) {
console.log(el);
var parent = el.find(".jFiler-jProgressBar").parent();
el.find(".jFiler-jProgressBar").fadeOut("slow", function () {
$("<div class=\"jFiler-item-others text-error\"><i class=\"icon-jfi-minus-circle\"></i> Error</div>").hide().appendTo(parent).fadeIn("slow");
});
},
statusCode: {},
onProgress: function () {},
},
dragDrop: {
dragEnter: function () {},
dragLeave: function () {},
drop: function () {},
},
addMore: true,
clipBoardPaste: true,
excludeName: null,
beforeShow: function () {
return true
},
onSelect: function () {},
afterShow: function () {},
onRemove: function (el) {
imageCounter = $('.img-container').size() - 1;
//uploadPosition();
//console.log(el.find('img').attr('src'));
},
onEmpty: function () {
imageCounter = 0;
},
captions: {
button: "Choose Files",
feedback: "Choose files To Upload",
feedback2: "files were chosen",
drop: "Drop file here to Upload",
removeConfirmation: "Are you sure you want to remove this file?",
errors: {
filesLimit: "Only {{fi-limit}} files are allowed to be uploaded.",
filesType: "Only Images are allowed to be uploaded.",
filesSize: "{{fi-name}} is too large! Please upload file up to {{fi-maxSize}} MB.",
filesSizeAll: "Files you've choosed are too large! Please upload files up to {{fi-maxSize}} MB."
}
}
});
});
Update
I have updated fiddle with HTML and CSS as well as javascript code, unfortunately, I couldn't get it to work, so not sure how helpful it is, but at least you can see the full code.
I am using this scripts on my page where I upload images:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js" integrity="sha384-I6F5OKECLVtK/BL+8iSLDEHowSAfUo76ZL9+kGAgTRdiByINKJaqTPH/QVNS1VDb" crossorigin="anonymous"></script>
<script type="text/javascript" src="{{ asset('js/foundation/foundation.min.js') }}"></script>
<script>$(document).foundation();</script>
<script type="text/javascript" src="{{ asset('js/jquery-ui/jquery-ui.min.js') }}"></script>
<script type="text/javascript" src="{{ asset('js/jquery-filer/jquery-filer.js') }}"></script>
jquery-filer is the script that I use for upload, the one that I have in fiddle.
And this is my server-side function for ajax upload. I am using PHP laravel in the backend:
public function ajaxUpload() {
if (Input::hasFile('file')) {
$files = Input::file('file');
foreach ($files as $file) {
$time = microtime(true);
$name = $file->getClientOriginalName();
$filename = $time.'-'.preg_replace('/[(\)\s]/u', '', $name);
if(substr($file->getMimeType(), 0, 5) == 'image') {
try {
$original = Image::make($file)->save(public_path($this->destinationPath.'/'.$filename));
\Log::info('try: '.$filename."\n");
} catch (Exception $e) {
\Log::info('Caught exception: '.$e->getMessage(). "\n");
}
$img = Image::cache(function($image) use ($original){
return $image->make($original);
});
}
}
}
return $this->destinationPath.$filename;
}
I have tried to salvage the problem part in your code and came up with this (Fiddle).
The problem part is probably in the success function. Instead of trying to get element by its index, use the 2nd argument passed to the success function.
success: function(data, el) {
uploadedImagesPositions = [];
var filenameArray = data.split('/');
var name = filenameArray.slice(-1).pop();
var filename = name.replace(/[\/\s()]/g, '');
// Instead of this
// var imageContainer = $('[data-jfiler-index="' + imageCounter + '"]').first();
// Use this
var imageContainer = el;
$('<div class="jFiler-item-thumb-image"><img src="/imagecache/thumb/' + filename + '"></div><div class="overlay"><span><i class="jFiler-item-trash-action ion-trash-a"></span></div>').appendTo(imageContainer );
}
The problem could also be caused by your server side, which we have no access right now.
Try to update to https://innostudio.de/fileuploader/ (jQuery.filer was transfered to the Fileuploader)
I was also using a JS image uploader which has the same type of issue. When a user uploads an image and deletes it and uploads the same image again, it does not work.
So I fixed it using:
$('input[type="file"]').val(null);
in the image deleted event.

Categories

Resources