Using scripts in Mvc Views without bundling - javascript

I want try using Rellax (javascript parallax library) in my MVC application at once of my views.
So I add the rellax.js script link (without bundling) and few lines script for rellax in #section scripts{<--->} at the target view.
Now when I trying to run console response a throw error
Uncaught Error: The elements you're trying to select don't exist.
at new g (rellax.min.js:1)
I read similar issue at Rellax Github and he said Use rellax.js without bundling per pages. But I used rellax.js and tags in one view without bundling
Here is my .cshtml
<div class="rellax-header rellax-header-sky" data-rellax-speed="-8" style="transform: translate3d(0px, 421px, 0px);">
<div class="page-header-image" style="background-image:url(#backPath)">
</div>
</div>
<div class="rellax-header rellax-header-buildings" data-rellax-speed="0" style="transform: translate3d(0px, 0px, 0px);">
<div class="page-header-image page-header-city" style="background-image:url(#imagePath)">
</div>
</div>
<div class="rellax-text-container rellax-text" style="transform: translate3d(0px, 128px, 0px);">
<h1 class="h1-seo" data-rellax-speed="-2">Test</h1>
<div class="pro">PRO</div>
</div>
#section Scripts {
<script src="~/js/plugins/rellax.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() >= 991) {
setTimeout(function () {
var rellax = new Rellax('.rellax', {
center: true
});
}, 5000);
var rellaxHeader = new Rellax('.rellax-header');
var rellaxText = new Rellax('.rellax-text');
}
});
</script>
}
Where is my wrong?
Any idea please?!

I was able to replicate the error locally. If you change your script tag to use the full version of rellax.js:
<script src="~/js/plugins/rellax.js" type="text/javascript"></script>
It will give you a stacktrace similar too:
rellax.js:100 Uncaught Error: The elements you're trying to select
don't exist.
at new Rellax (rellax.js:100)
at Index:68
Index:68 for me is:
var rellax = new Rellax('.rellax', {
This is because there is no element with a class of 'rellax'
To fix the error, I changed the first div too:
<div class="rellax rellax-header-sky" data-rellax-speed="-8">
So that there was an element with a class of 'rellax'

Related

document.querySelector() does not working

Is there any dependency problem?
because I am using the only pure javascript there is no jquery or anything.
Using node.js
Here is my code
window.onload()=function(){
var left=document.querySelector('.left');
var right=document.querySelector(".right");
var container=document.querySelector(".container");
console.log(left);
left.addEventListener('mouseenter',()=>{
container.classList.add('hover-left');
})
left.addEventListener('mouseleave', () => {
container.classList.remove('hover-left');
})
right.addEventListener('mouseenter', () => {
container.classList.add('hover-right');
})
right.addEventListener('mouseleave', () => {
container.classList.remove('hover-right');
})
}
<div class="container">
<div class="split left">
<h1>The Designer</h1>
Read more
</div>
<div class="split right">
<h1>The Programmer</h1>
Read more
</div>
</div>
I got this error on Chrome:
Uncaught TypeError: window.onload is not a function
Removing the parentheses the error was gone.
But i didn't get how your page should work.
Look for more information here:
https://stackoverflow.com/questions/29927638/window-onload-work-but-chrome-console-says-uncaught-typeerror-window-onload-is
If you select your DOM Elements with the CSS-Selector '.' for classes you get a list of elements instead of a single element which you can directly manipulate.
If left, right and container only appear once on your page, it's best to use ids:
JS:
window.onload=function(){
var left=document.getElementById('left');
var right=document.getElementById("right");
var container=document.getElementById("container");
console.log(left);
left.addEventListener('mouseenter',()=>{
container.classList.add('hover-left');
})
left.addEventListener('mouseleave', () => {
container.classList.remove('hover-left');
})
right.addEventListener('mouseenter', () => {
container.classList.add('hover-right');
})
right.addEventListener('mouseleave', () => {
container.classList.remove('hover-right');
})
}
HTML:
<div id="container" class="container">
<div class="split" id="left">
<h1>The Designer</h1>
Read more
</div>
<div class="split" id="right">
<h1>The Programmer</h1>
Read more
</div>
</div>
Also as a comment above points out you mustn't use brackets when setting onload event.
If you have any static JS files being loaded in the tag in your html requesting to please load the JS at the end of the html body. Document wont be ready until the JS is loaded hence the document will be null.

How do I debug in chrome to get value of an observable in knockout?

I am working on a video player app and It has multiple play buttons and each time I hit a play button loggerVideoURL takes in a url I want to find the value of loggerVideoURL.
How do I debug to find the value of loggerVideoURL at each instance of hitting the play button.
Here's my code
HTML
<div class="loggerVideoControlsWrapper p0" id="video-controls-wrapper" style="">
<!-- Video -->
<div class="video-js-responsive-container vjs-hd" id="video-container">
<video crossorigin="anonymous" id="logger-media-player" preload="auto" data-bind="attr:{src:loggerVideoURL},event:{timeupdate:onPlayerTimeUpdate,play:playerOnPlay,pause:playerOnPause,seeked:playerOnSeeked,seeking:playerOnSeeking,loadedmetadata:playerOnLoadedmetadata,error:playerOnError}" class="video-js vjs-default-skin" width="auto" height="auto">
#*controls="true" - for now *#
#*<source data-bind="attr:{src:loggerVideoURL}" type="video/mp4" />*#
#*<track label="English" srclang="en" kind="captions" data-bind="attr:{src:captionsFileUrl}" />*#
</video>
<div data-bind="if: playerSeeking() || !playerLoadedMetadataFired() || playerErrorMsg()">
<div id="seeking-overlay">
<div class="snippet-demo" data-bind="if: !playerErrorMsg()" style="position: relative; top: 50%; transform: translateY(-50%);">
<div class="snippet-demo-container demo-spinner demo-spinner__spinner-default">
<!-- MDL Spinner Component -->
<div class="mdl-spinner mdl-js-spinner is-active is-upgraded" data-upgraded=",MaterialSpinner"><div class="mdl-spinner__layer mdl-spinner__layer-1"><div class="mdl-spinner__circle-clipper mdl-spinner__left"><div class="mdl-spinner__circle"></div></div><div class="mdl-spinner__gap-patch"><div class="mdl-spinner__circle"></div></div><div class="mdl-spinner__circle-clipper mdl-spinner__right"><div class="mdl-spinner__circle"></div></div></div><div class="mdl-spinner__layer mdl-spinner__layer-2"><div class="mdl-spinner__circle-clipper mdl-spinner__left"><div class="mdl-spinner__circle"></div></div><div class="mdl-spinner__gap-patch"><div class="mdl-spinner__circle"></div></div><div class="mdl-spinner__circle-clipper mdl-spinner__right"><div class="mdl-spinner__circle"></div></div></div><div class="mdl-spinner__layer mdl-spinner__layer-3"><div class="mdl-spinner__circle-clipper mdl-spinner__left"><div class="mdl-spinner__circle"></div></div><div class="mdl-spinner__gap-patch"><div class="mdl-spinner__circle"></div></div><div class="mdl-spinner__circle-clipper mdl-spinner__right"><div class="mdl-spinner__circle"></div></div></div><div class="mdl-spinner__layer mdl-spinner__layer-4"><div class="mdl-spinner__circle-clipper mdl-spinner__left"><div class="mdl-spinner__circle"></div></div><div class="mdl-spinner__gap-patch"><div class="mdl-spinner__circle"></div></div><div class="mdl-spinner__circle-clipper mdl-spinner__right"><div class="mdl-spinner__circle"></div></div></div></div>
</div>
</div>
<!-- ko if: playerErrorMsg() -->
<div data-bind="" class="alert alert-danger alert-dismissable" style="width: 75%;margin: auto auto;position: relative; top: 50%; transform: translateY(-50%);">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<h4><i class="fa fa-times-circle"></i> Error</h4> <span data-bind="text:playerErrorMsg" style="font-weight: normal"></span>
</div>
<!-- /ko -->
</div>
</div>
</div>
JavaScript
function ClsLoggerVideo(parent) {
var self = this;
var timer;
var timerInterval = 800;
var FrameRate = TimecodeMath.FrameRate;
function log(msg) { console.log(msg); }
$(document).on('mouseup', function () { clearInterval(timer); });
self.isIe = vmsWebUtils.isIE();
self.parentLogger = ko.observable(parent);
self.captionFiles = ko.observableArray();
self.loggerVideoURL = ko.observable();
//self.captionsFileUrl = ko.observable('http://ny-venturae-7.viacom_corp.ad.viacom.com/video/APOCALYPSE_NOW_1080p2398_CLIP.vtt');
self.captionFiles.push();
self.techAttributes = ko.observable(null);
self.frameRate = ko.computed(function () { return self.techAttributes() == null ? null : self.techAttributes().frameRate; });
self.isDropFrame = ko.computed(function () {
return self.techAttributes() == null ? null : self.techAttributes().isDropFrame;
});
self.startTcInFrames = ko.computed(function () {
return self.techAttributes() == null ? null : self.techAttributes().startTcInFrames;
});
I'm not sure on whether you're asking how to debug in Chrome, or how to get the value in Knockout, so I'll throw out some info and hope it answers your question.
Debugging in Chrome:
Open the developer tools (More Tools > Developer Tools).
Go to the Sources tab.
In the left window pane open the folder that contains your Javascript files (may be called "js" for example, but will depend on your folder naming structure in your web app).
Click on the .js file that contains your Knockout viewmodel definition. In this case that would be the one that contains the function ClsLoggerVideo.
Then find where you want to set a breakpoint in the .js file and simply click on the line number.
When you run the function again it will break at that spot and you can hover over values or add watches by highlighting right clicking a variable. In this case loggerVideoURL.
Keep in mind with Knockout, you need to make the watch like this: self.loggerVideoURL()
You need to include the parentheses to get the underlying value of the observable. If you don't include them the you'll just see the KO observable function definition.
As far as your code is concerned I'm seeing multiple issues. First, I don't see where you handle the Play button press. You could do this any number of ways in Javascript, but since you're using KO I'd suggest using a click event binding like this:
<button type="button" data-bind="click: playButtonClicked">Play</button>
Then in your viewmodel function ClsLoggerVideo, put this:
self.playButtonClicked = function () {
//Put some code here to land a breakpoint on so you can see the value of loggerVideoURL()
}
I hope that helps.
The Knockout Context Debugger chrome extension is extremely helpful. You can open dev tools as usual, but there is a new subtab for inspecting bound elements and the backing viewmodel. This approach doesn't require any breakpoints.

Equivalent of getElementById in Angular?

I'm moving some of my html/javascript pages over to AngularJS. Previously, my script (an HTML5 audio player) rendered some HTML elements on the page and then ran some script to use those elements, thusly:
audioplayer.html:
...
<div id="timeline">
<div id="showElapsed">
<div class="bg">
</div>
</div>
<div id="playhead"></div>
</div>
...
<script>
var playhead = document.getElementById('playhead'); // playhead
var timeline = document.getElementById('timeline'); // timeline
// timeline width adjusted for playhead
var timelineWidth = timeline.offsetWidth - playhead.offsetWidth;
...
Now i'd like to move this into a controller / view layout in angular, so;
index.html
...
<div ng-controller="AudioPlayerController">
<div ng-include="'views/audioPlayerView.html'"></div>
</div>
...
main.js
...
function AudioPlayerController($scope) {
var playhead = document.getElementById('playhead'); // playhead
var timeline = document.getElementById('timeline'); // timeline
// timeline width adjusted for playhead
var timelineWidth = timeline.offsetWidth - playhead.offsetWidth;
...
audioPlayerView.html:
...
<div id="timeline">
<div id="showElapsed">
<div class="bg">
</div>
</div>
<div id="playhead"></div>
</div>
...
Now I have a problem - document.getElementById('timeline'); doesn't return anything because its moved to a controller. Furthermore, the controller is called BEFORE the view, so how can the controller reference an element FROM the view?
I realize this is basic Angular layout stuff, but I can't figure it out. Could someone help me think in a more angular way please!? Thanks.
For dom interaction in angular you have directives elements
that implemented in the view.
directive link also complie after view is loaded, so no problem here.
note their declarations are written in camel case on the view, so:
javascript:
angular.module('myApp')
.directive('audioPlayer', function() {
return {
restrict: 'A',
template: 'path-to-your-page/audioPlayerView.html',
link: function(element) {
var playhead = element.find('playhead');
// timeline width adjusted for playhead
var timelineWidth = element.offsetWidth - playhead.offsetWidth;
}
};
});
html:
<div audio-player>
<div id="showElapsed">
<div class="bg">
</div>
</div>
<div id="playhead"></div>
</div>
note that,
in "angular way" you shouldn't make
document.getElementById(), just ==> angular.element()

Uncaught TypeError: $(...).sidr is not a function[Console Chrome developer tool]

I put this code into add basic module HTML block of a wordpress page builder. I encounter the white screen of death. Chrome developer console told me the following:
helpers.js?ver=4.5.3:15 Uncaught TypeError: $(...).sidr is not a function
This can be traced from line 15 in helpers.js?ver=4.5.3:
$('#mobile-menu-trigger').sidr({
source: sourceVal,
name: 'sidr-main'
});
Before or after I restored the previous version of the page, there was no such error. The html code below seems to run normally if save as a html file and open it with chrome. Can someone please explain which might have possibly caused that error?
Edit: When I change the theme of wordpress, everything works again. With all of other themes, the code works so the problem should come from the theme.
$(document).ready(function() {
getUpdates();
});
function getUpdates() {
// get the data with a webservice call
$.getJSON('http://api.thingspeak.com/channels/136053/feed/last.json?callback=?', function(data) {
// if the field1 has data update the page
if (data.field1) {
document.querySelector('.info-giver .temperature').innerHTML = data.field1.slice(0,4) + "°C";
document.querySelector(".info-giver .humidity").innerHTML = data.field2.slice(0,5) + "%";
document.querySelector('.info-giver .windspeed').innerHTML = data.field4.slice(0,4) +" m/s";
document.querySelector(".info-giver .pressure").innerHTML = data.field3 +"Pa" ;
}
});
}
(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class = "announcer">
<div class="temperatureDeclared" style= "width: 25.00%">Temperature</div>
<div class="humidityDeclared" style= "width: 25.00%">Humidity</div>
<div class="windspeedDeclared" style= "width: 25.00%">Windspeed</div>
<div class="pressureDeclared" style= "width: 25.00%">Pressure</div>
</div>
<div class = "info-giver">
<div class="temperature" style= "width: 25.00%">N/a</div>
<div class="humidity" style= "width: 25.00%">N/a</div>
<div class="windspeed" style= "width: 25.00%">N/a</div>
<div class="pressure" style= "width: 25.00%">N/a</div>
</div>
Add these lines before and after code your code will works
;(function($){
//code
})(jQuery);
Just Like This
;(function($){
$('#mobile-menu-trigger').sidr({
source: sourceVal,
name: 'sidr-main'
});
})(jQuery);
I hope this will works !
You didn't include your sidr library. After loading jquery include sidr library. After that init sidr like this on your html.
$('#mobile-menu-trigger').sidr({....});

TypeError: container.montage is not a function max: 300

I have the following Jquery Code and it is an error
$container.montage is not a function
I am following this library , and my browser is not showing any other errors. I have already checked that I am loading the required library from FireBug and still can't figure out what is wrong here.
$(function() {
var $container = $('#am-container'),
$imgs = $container.find('img').hide(),
totalImgs = $imgs.length,
cnt = 0;
$imgs.each(function(i) {
var $img = $(this);
$('<img/>').load(function() {
++cnt;
if (cnt === totalImgs) {
$imgs.show();
$container.montage({
fillLastRow: true,
alternateHeight: true,
alternateHeightRange: {
min: 75,
max: 300
}
});
/*
* just for this demo:
*/
$('#overlay').fadeIn(500);
}
}).attr('src', $img.attr('src'));
});
});
And this is my HTML
<div class="main-gallary">
<div class="container">
<div id="am-container" class="am-container">
<a href="#">
<img class="ui-draggable" src="images/gallary/img-1.jpg" style="display: inline; position: relative;">
</a>
<a href="#">
<a href="#">
</div>
</div>
</div>
In your HTML document you should have similar lines to the following before the rest of your code.
To load jQuery (which you probably already have):
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
To load the jQuery Montage Plugin:
<script type="text/javascript" src="js/jquery.montage.min.js"></script>
The src="js/jquery.montage.min.js" needs to be correct for where the file is located. Using that path you would upload it to a folder called js on your web-server.

Categories

Resources