javascript not working when added via asset pipeline - javascript

I want to implement bootstrap themes to my rails application
http://startbootstrap.com/template-overviews/creative/
in that theme there is a file named creative.js
I have add it to my application via asset pipeline
and when I load the page and use inspect element I can see it under sources tab and I can open it
But the script not worked
but If I copy paste the code and put it in my html It worked properly
my application.js
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require bootstrap-sprockets
//= require creative
//= require_tree .
creative.js
(function($) {
"use strict"; // Start of use strict
// jQuery for page scrolling feature - requires jQuery Easing plugin
$('a.page-scroll').bind('click', function(event) {
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: ($($anchor.attr('href')).offset().top - 50)
}, 1250, 'easeInOutExpo');
event.preventDefault();
});
// Highlight the top nav as scrolling occurs
$('body').scrollspy({
target: '.navbar-fixed-top',
offset: 51
});
// Closes the Responsive Menu on Menu Item Click
$('.navbar-collapse ul li a').click(function() {
$('.navbar-toggle:visible').click();
});
// Offset for Main Navigation
$('#mainNav').affix({
offset: {
top: 100
}
})
// Initialize and Configure Scroll Reveal Animation
window.sr = ScrollReveal();
sr.reveal('.sr-icons', {
duration: 600,
scale: 0.3,
distance: '0px'
}, 200);
sr.reveal('.sr-button', {
duration: 1000,
delay: 200
});
sr.reveal('.sr-contact', {
duration: 600,
scale: 0.3,
distance: '0px'
}, 300);
// Initialize and Configure Magnific Popup Lightbox Plugin
$('.popup-gallery').magnificPopup({
delegate: 'a',
type: 'image',
tLoading: 'Loading image #%curr%...',
mainClass: 'mfp-img-mobile',
gallery: {
enabled: true,
navigateByImgClick: true,
preload: [0, 1] // Will preload 0 - before current, and 1 after the current image
},
image: {
tError: 'The image #%curr% could not be loaded.'
}
});
})(jQuery); // End of use strict
my application.html.erb
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Creative - Start Bootstrap Theme</title>
<%= csrf_meta_tags %>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Merriweather:400,300,300italic,400italic,700,700italic,900,900italic' rel='stylesheet' type='text/css'>
<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body id="page-top">
<%= yield %>
<script>
creative.js code here
</script>
</body>
</html>

change the firstline in creative.js seems to fix this problem
from
(function($) {
into
$(function() {
and the last line from })(jQuery); into });
External JS/jQuery files are loading but not executing
creative.js
$(function() {
"use strict"; // Start of use strict
// jQuery for page scrolling feature - requires jQuery Easing plugin
$('a.page-scroll').bind('click', function(event) {
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: ($($anchor.attr('href')).offset().top - 50)
}, 1250, 'easeInOutExpo');
event.preventDefault();
});
// Highlight the top nav as scrolling occurs
$('body').scrollspy({
target: '.navbar-fixed-top',
offset: 51
});
// Closes the Responsive Menu on Menu Item Click
$('.navbar-collapse ul li a').click(function() {
$('.navbar-toggle:visible').click();
});
// Offset for Main Navigation
$('#mainNav').affix({
offset: {
top: 100
}
})
// Initialize and Configure Scroll Reveal Animation
window.sr = ScrollReveal();
sr.reveal('.sr-icons', {
duration: 600,
scale: 0.3,
distance: '0px'
}, 200);
sr.reveal('.sr-button', {
duration: 1000,
delay: 200
});
sr.reveal('.sr-contact', {
duration: 600,
scale: 0.3,
distance: '0px'
}, 300);
// Initialize and Configure Magnific Popup Lightbox Plugin
$('.popup-gallery').magnificPopup({
delegate: 'a',
type: 'image',
tLoading: 'Loading image #%curr%...',
mainClass: 'mfp-img-mobile',
gallery: {
enabled: true,
navigateByImgClick: true,
preload: [0, 1] // Will preload 0 - before current, and 1 after the current image
},
image: {
tError: 'The image #%curr% could not be loaded.'
}
});
}); // End of use strict

Related

jquery $ is not defined despite that jquery loaded before main.js

I use smoothstate.js, dispte that my jquery cdn is before my main.js it still give me an error $ is not defined
My scripts loading order:
<!-- jquery -->
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<!--Smoothstate.js -->
<script src="../assets/scritps/jquery.smoothState.min.js"></script>
<!-- Script tags -->
<script src="../assets/scritps/main.js"></script>
Here is my code:
$(function(){
'use strict';
var $page = $('#main'),
options = {
debug: true,
prefetch: true,
cacheLength: 2,
onStart: {
duration: 250, // Duration of our animation
render: function ($container) {
// Add your CSS animation reversing class
$container.addClass('is-exiting');
// Restart your animation
smoothState.restartCSSAnimations();
}
},
onReady: {
duration: 0,
render: function ($container, $newContent) {
// Remove your CSS animation reversing class
$container.removeClass('is-exiting');
// Inject the new content
$container.html($newContent);
}
}
},
smoothState = $page.smoothState(options).data('smoothState');
});

Load external javascript to component dynamically

I am trying to load an external library (Javascript) to an Angular2 component (TypeScript).
Take example: https://github.com/fengyuanchen/cropperjs
My approach:
index.html
<head>
<link href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/0.8.1/cropper.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/0.8.1/cropper.js"></script>
</head>
myCropper.js
window.addEventListener('DOMContentLoaded', function () {
var image = document.querySelector('#image');
var cropper = new Cropper(image, {
viewMode: 3,
dragMode: 'move',
autoCropArea: 1,
restore: false,
modal: false,
guides: false,
highlight: false,
cropBoxMovable: false,
cropBoxResizable: false,
toggleDragModeOnDblclick: false,
});
});
photo.component.ts
#Component({
selector: 'photo-crop',
template: `
<div class="row">
<img id="image" src="http://img01.ibnlive.in/ibnlive/uploads/875x584/jpg/2015/09/new-google-logo-010915.png" class="img-responsive"/>
<div class="row">
`,
styles: []
})
export class PhotoComponent {
public ngOnInit() {
this.loadScript('src/assets/js/myCropper.js');
});
}
public loadScript(url) {
console.log('preparing to load...')
let node = document.createElement('script');
node.src = url;
node.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(node);
}
}
Problem: the image is loaded without zoom/crop effect. I inspected the page and saw the script was added correctly in . I refreshed page, no luck. I had no error at all. It seems Angular2 does not activate the script.
I also tried a workaround: putting script in index.html directly (This workaround return error when the page is not loaded yet)
<head>
...
<script src="src/assets/js/myCropper.js"></script>
</head>
Photo is loaded without zoom/crop effect at start. But after I refresh the page, zoom/crop effect is activated. This is not a good practice where all scripts kept in index.html, but at least the script works after refresh.
Any suggestion is appreciated.

Cannot read property 'parseMetaData' of undefined in Modal

I try to use jQuery file upload in a bootstrap modal with external content.
I've no problem with Firefox and Explorer, but with Chrome i've got this error
Cannot read property 'parseMetaData' of undefined
I include jQuery.js and jQuery.ui.min.js in main template and all other js directly in php page called by modal in this order:
<script src="//blueimp.github.io/JavaScript-Templates/js/tmpl.min.js"></script>
<script src="//blueimp.github.io/JavaScript-Load-Image/js/load-image.all.min.js"></script>
<script src="//blueimp.github.io/JavaScript-Canvas-to-Blob/js/canvas-to-blob.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script src="//blueimp.github.io/Gallery/js/jquery.blueimp-gallery.min.js"></script>
<script src="js/jquery.iframe-transport.js"></script>
<script src="js/jquery.fileupload.js"></script>
<script src="js/jquery.fileupload-process.js"></script>
<script src="js/jquery.fileupload-image.js"></script>
<script src="js/jquery.fileupload-audio.js"></script>
<script src="js/jquery.fileupload-video.js"></script>
<script src="js/jquery.fileupload-validate.js"></script>
<script src="js/jquery.fileupload-ui.js"></script>
Then there is my code:
jQuery(function ($) {
'use strict';
$('#fileupload').fileupload({
autoUpload: true,
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
maxFileSize: 8000000,
maxNumberOfFiles: 6,
disableImageResize: /Android(?!.*Chrome)|Opera/
.test(window.navigator && navigator.userAgent),
imageMaxWidth: 1200,
imageMaxHeight: 900,
imageCrop: false,
url: '/wall/'
});
$('#fileupload').fileupload(
'option',
'redirect',
window.location.href.replace(
/\/[^\/]*$/,
'/cors/result.html?%s'
)
);
});
Anyone could help me?
i found the answer!
I've to include all the scripts in the header of main template.
Bye

OKZoom, jQuery, and Rails

I am trying to implement okzoom in my rails application but I don't seem to be having much luck. Everything appears to be ok. I've added the javascript file to my javascripts directory (app/assets/javascripts/okzoom.js) and also tried using the okzoom_rails gem just to err on the side of caution. The code editor appears to resolve the okzoom function with no problem but when I run the site, I see the following console error:
Uncaught TypeError: undefined is not a function
And if I use the Chrome debug tools to dig into it, the problem is clearly with my call to okzoom - for some reason the website isn't seeing it.
Here is my application.js file:
//= require jquery
//= require jquery_ujs
//= require fancybox
//= require okzoom
//= require turbolinks
//= require_tree .
$("a.fancybox")
.fancybox( {
'transitionIn': 'elastic',
'transitionOut': 'elastic',
helpers : {
title : {
type: 'inside'
}
},
beforeShow: function() {
/*disable right click*/
$.fancybox.wrap.bind("contextmenu", function (e){
return false;
});
}
});
$("img.zoomable")
.okzoom({
width: 200,
height: 200,
round: true,
background: "#ffffff",
backgroundRepeat: "repeat",
shadow: "0 0 5px #000000",
border: "1px solid black"
});
I have no issues with the fancybox implementation and I followed the same pattern for okzoom but with no luck. Anyone have any ideas?
UPDATE
Here is the code for zoomable image:
<%= image_tag(p.file_info.fullPath, class: "zoomable") %>
It's very possible that by the time the JavaScript interpreter gets to the line that loads okzoom that okzoom hasn't already been fetched from the server. I would suggest wrapping your code like the following:
$(document).ready(function() {
$("a.fancybox")
.fancybox( {
'transitionIn': 'elastic',
'transitionOut': 'elastic',
helpers : {
title : {
type: 'inside'
}
},
beforeShow: function() {
/*disable right click*/
$.fancybox.wrap.bind("contextmenu", function (e){
return false;
});
}
});
$("img.zoomable")
.okzoom({
width: 200,
height: 200,
round: true,
background: "#ffffff",
backgroundRepeat: "repeat",
shadow: "0 0 5px #000000",
border: "1px solid black"
});
});
The ready event is triggered once all of the website's markup and assets have been downloaded from the server.

soundmanager2.js + require.js not working with firefox + adblock plus

can't get the following test to work with Firefox 22.0 when AdBlock Plus is enabled. Works just fine on Chrome + when I've disabled adblock. It also works when I'm loading the scripts with script tags instead of requirejs.
./index.html:
<!DOCTYPE html>
<html>
<head>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=ISO-8859-1">
<link rel="stylesheet" type="text/css" href="css/main.css"/>
<!--<link rel="icon" type="image/png" href="img/icon.png"/>-->
<!--<script src="js/lib/jquery.js"></script>-->
<script data-main="js/main" src ="require.js"></script>
<!--
<script src="js/lib/soundmanager2.js"></script>
<script src="js/test.js"></script>
-->
<title></title>
</head>
<body>
<div id="stop" style="cursor:pointer;"> stop</div>
</body>
</html>
./js/main.js:
require.config({
paths:{
jquery:"lib/jquery",
underscore:"lib/underscore",
soundmanager2:"lib/soundmanager2"
/*backbone:"lib/backbone",
detectmobilebrowser:"lib/detectmobilebrowser"*/
},
shim: {
'underscore': {
exports: '_'
},
'soundmanager2':{
exports:"soundManager"
}
}
});
define(['jquery','underscore',"soundmanager2"],
function($,_,soundManager){
alert("hep");
window.soundManager=soundManager;
soundManager.setup({
url: 'swf',
useHTML5Audio:true,
preferFlash: false, // prefer 100% HTML5 mode, where both supported
onready: function() {
alert('SM2 ready!');
/*
soundManager.createSound({
id: 'mySound',
url: './test/test.mp3',
autoLoad: true,
autoPlay: false,
onload: function() {
soundManager.play('mySound');
},
volume: 50
});
*/
},
ontimeout: function() {
alert('SM2 init failed!');
},
defaultOptions: {
// set global default volume for all sound objects
volume: 100
}
});
$("#stop").on("click",function(){
alert("stop");
soundManager.stop("mySound");
});
return soundManager;
});
No errors or anything in the console, no alerts after that initial 'hep!' one.
Classic pattern, fight with some issue for hours, give up and ask for help, find solution immediately after posting.
added
soundManager.beginDelayedInit();
after soundManager.setup() and it works now.
Use require () method of RequireJS to load a module. In the callback write your code what need. Note that parameter of function is a array contains paths that loads dependencies
require.config({
paths:{
jquery:"lib/jquery",
underscore:"lib/underscore",
soundmanager2:"lib/soundmanager2"
/*backbone:"lib/backbone",
detectmobilebrowser:"lib/detectmobilebrowser"*/
},
shim: {
'underscore': {
exports: '_'
},
'soundmanager2':{
exports:"soundManager"
}
}
});
require(['jquery','underscore',"soundmanager2"],function($,_,soundManager){
alert("hep");
window.soundManager=soundManager;
soundManager.setup({
url: 'swf',
useHTML5Audio:true,
preferFlash: false, // prefer 100% HTML5 mode, where both supported
onready: function() {
alert('SM2 ready!');
/*
soundManager.createSound({
id: 'mySound',
url: './test/test.mp3',
autoLoad: true,
autoPlay: false,
onload: function() {
soundManager.play('mySound');
},
volume: 50
});
*/
},
ontimeout: function() {
alert('SM2 init failed!');
},
defaultOptions: {
// set global default volume for all sound objects
volume: 100
}
});
$("#stop").on("click",function(){
alert("stop");
soundManager.stop("mySound");
});
});

Categories