I have a template that I am using from template monster. In the files there is a javascript page that has all of the scripts needed to run the pages. I have added this to the bottom of the page where the scripts are rendered. It does not seem to be accessing the file. It is on the page and comes up when I am viewing it under the "Inspect object". When I put the code snippet directly in the razor page it works. Any ideas why it would not be pulling it from the javascript file? Thanks for your help.
EDIT
This resides in the _Layout page. Where the Menu is.
The below works when inserted in the razor page.
<script type="text/javascript">
$(document).ready(function () {
$(".sticky-menu").sticky({ topSpacing: 0 });
});
$(window).on('load', function () {
function fadeOut(el) {
el.style.opacity = 0.4;
var last;
var tick = function () {
el.style.opacity = +el.style.opacity - (new Date() - last) / 600;
last = +new Date();
if (+el.style.opacity > 0) {
(window.requestAnimationFrame && requestAnimationFrame(tick)) || setTimeout(tick, 100);
} else {
el.style.display = "none";
}
};
tick();
}
var pagePreloaderId = document.getElementById("page-preloader");
setTimeout(function () {
fadeOut(pagePreloaderId)
}, 1000);
});
</script>
This is what I have in the razor page that does not work
#Scripts.Render("~/Scripts/scripts.js")
The Top code resides in the "scripts.js" file.
There is a lot of code in this file and it seems like none of it is working. Meaning it is like it is not accessing the script. All the scripts that are loaded in the page are in the same order as the Regular HTML in the template. The template HTML file works.
UPDATE -
I got this to work by moving this out of the script page and onto the layout page. I am still not sure why or what was causing this snippet not to work in the script page. It seems like the only part that wasnt working.
In the script file it is written like this:
(function($) {
'use strict';
jQuery(document).on('ready', function() {
////// Other snippets //////
$(".sticky-menu").sticky({
topSpacing: 0
});
////// Other snippets //////
});
In the _Layout page it looks like this:
<script type="text/javascript">
$(document).ready(function () {
$(".sticky-menu").sticky({ topSpacing: 0 });
var hub = $.connection.notificationHub;
$.connection.hub.start()
.done(function () {
console.log("Hub Connected!");
})
.fail(function () {
console.log("Could not Connect!");
});
});
</script>
I still do not know why this does not work from the Script file...
UPDATE - 4-26-2019
I have found the problem. The Template was created with a earlier version of jQuery. I have found that the Script file loads and partially works when I remove
jQuery(document).on('ready', function () {
The entire file looks like this
(function($) {
'use strict';
jQuery(document).on('ready', function () {
---> All the jQuery Code
});
})(jQuery);
I changed the above line to be:
}(jQuery));
I saw some other implementations that had it this way.
However there is something not right with this using jQuery 3.3.1.. if anyone knows how to properly format this so it works that would help alot.
You change from
#Scripts.Render("~/Scripts/scripts.js")
to
<script src="~/Scripts/scripts.js"></script>
It will work
You can refer this link to understand different between Script.Render vs script tag
What is the difference between "#Script.Render" and "<script>"?
Update:
If you have a _Layout.cshtml view like this
<html>
<body>
#RenderBody()
#RenderSection("scripts", required: false)
</body>
</html>
then you can have an index.cshtml content view like this
#section scripts {
<script type="text/javascript" src="~/Scripts/scripts.js"></script>
}
Related
I have a /js/common.js file attached in the <head> of my webpage, and then the file for my page /about.aspx.
<script src='/js/common.js'></script>
<script src='/js/modernizr-custom.js'></script>
<script type="text/javascript" src="//code.jquery.com/jquery-1.11.0.min.js"></script>
I can hear how dumb this question is, and I do apologise, but it is annoying me as to why I can not figure it out.
This code here shows and hides the navigation:
var didScroll;
/* more variables .. */
$(window).scroll(function (event) {
didScroll = true;
});
setInterval(function () {
if (didScroll) {
hasScrolled();
didScroll = false;
}
}, 250);
function hasScrolled() {
var st = $(this).scrollTop();
/* Rest of code */
}
And my common.js file has the following structure:
// Declarations
var pageLoaded = false;
var fontsLoaded = false;
// Wrapper
function wrapperWidth() {
return parseFloat(document.getElementById("wrapper").offsetWidth);
}
// And so on..
//-----------------------
// jQuery Initialisation
//-----------------------
$(document).ready(function () {
//Set variables on page load
$(window).load(function () {
pageLoaded = true;
fontsLoaded = true;
});
});
If I place my js to hide the menu on scroll within the external .js file common.js, the javascript does not work and I don't know why?
At present, I place it right before the closing </body> tag on each page.
I wish to be able to place my javascript in one place 1) so that it can be easily found for maintenance and 2) most importantly, to speed up load time, as the more <script></script> tags one has, will slow down page load.
Can someone please explain why my 'menu hide' javascript will not work when I place within my common.js file?
Check if you called properly your common.js and jquery min.js
Call it in below given order
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.3/jquery.min.js"></script>
<script type="text/javascript" src="js/common.js"> </script>
In my one of the PHP project, part of it done by some other people. All the js scripts are loaded in footer file. The html closes at the footer file.
How Can I use jquery functions before the inclusion of footer file ?. Since using it after the footer file will show it after the closing of html. When I tired to use jquery functions before the footer I get the js error $ not defined etc.. I have searched many similar questions but couldn't find a solution. I can't change the file inclusion order currently since some other people have done it. Any help will be appreciated.
If, like you mention, you have absolutely no control over where jQuery scripts are included, you can set timer to check when jQuery is ready, e.g.:
<script>
var i = setInterval(function() {
if ($) {
clearInterval(i);
$(document).ready(function(){
alert('Ready!');
})
}
}, 100)
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
But otherwise - if you can control it - include them before your code.
this code will only run properly in modern browsers (IE > 8)
<div class="jq"></div>
<script>
document.addEventListener('DOMContentLoaded', function(){
$('.jq').html('working');
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Example - http://jsfiddle.net/2mmdrega/
I sometimes did something like this:
function JQueryManager(callback, thisArgument) {
this.execute = function() {
if (typeof jQuery == "undefined") {
console.log("Waiting for jQuery...");
var self = this;
var selfArgs = arguments;
setTimeout(function() {
self.execute(selfArgs)
}, 100)
} else {
console.log("Found jQuery. Version: " + jQuery.fn.jquery);
callback.apply(thisArgument, arguments)
}
}
}
function myCallback(results) {
alert("found " + results.length + " results")
}
var jQueryManager = new JQueryManager(myCallback);
jQueryManager.execute($("div"));
That allows you to execute a callabck function when jQuery is available
EDIT: fixed some copy-paste errores
Hello everyone,
I have just recently started learning the require.js , but I don't seem to understand as how does the whole mechanism work...and especialy how do I access the variables/objects created using this javascript library.
Let me explain it further in the example below..
webroot/page.jsp
<html>
<script data-main="js/page" src="js/lib/require.js"></script>
</html>
webroot/js/common.js
requirejs.config({
baseUrl: 'js/lib',
paths: {
app: '../app',
}
});
webroot/js/app/page.js
require(['./common'], function (common) {
require(['./app/page/init'], function(page)
{
page.load(1);
});
});
webroot/js/app/page/init.js
define(['./load'], function (load) {
var LoadPage = new load();
return LoadPage;
});
webroot/js/app/page/load.js
define(function () {
function loadPage() {
}
loadPage.prototype = {
load: function (page_id) {
console.log("Opening page "+page_id+" ");
}
};
return loadPage;
});
now when I run the page everything works perfectly, but now I'd like to execute the load method by clicking on a button.
<div onclick="page.load(2);"> </div>
but this does not work..So I'd like to know if there is any possibility to bind this action to any button or link...whatever..
(apologies for my bad english)
Thanks,
Alex
How about as below assuming you are using JQuery:
<div id="divPageLoad"></div>
<script language="javascript" type="text/javascript">
$("#divPageLoad").on("click", function() {
page.load(2);
});
</script>
In my website, there include such 2 files: index.php, script.js
Of course, it is much more complicated in the web site and the above only shows a part of it.
In index.php, there is a div element
<div id="phb29" class="drag ph hour01">Testing</div>
In script.js,which is a pure javascipt file,below show a part that i want to use a jquery function .switchClass() (from http://api.jqueryui.com/switchClass/) to switch the class of div element.
//... other normal js codes
switchClassHour = function(){
$(function (){
$( "#phb29" ).switchClass( "hour01", "hour03", 1000 );
return false;
});
}
//other normal js codes...
I only want to call that jquery when I call the switchClassHour() function but not the web page is loaded(i.e. $(document).ready(function (){...}); )
I have included the source in the in index.php:
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script type="text/javascript" src="script.js"></script>
But finally, the chrome browser gives me this error occurring at the line $(function (){ when I trigger switchClassHour():
Uncaught TypeError: boolean is not a function
What should I do, thank you !!!!! :):)
The variable toHour does not appear to be defined within the function switchClassHour.
Try this
switchClassHour = function(){
/* `toHour` ? */
if (window.jQuery) {
/* $(function (){ */
$( "#phb29" ).switchClass( "hour01", "hour03", 1000 );
/* `return false;` ? */
/* }); */
};
};
switchClassHour(); /* just noticed, is the function actually called ? */
Edit
Try this
switchClassHour = function(){
/* `toHour` ? */
if (window.jQuery) {
/* $(function (){ */
console.log($.now())
/* `return false;` ? */
/* }); */
};
};
switchClassHour();
Is $.now() return'ed at console?
Is $ utilized in other parts of non-jquery pieces?
See also https://api.jquery.com/jQuery.noConflict/
Edit
Try this
switchClassHour = function() {
jQuery.noConflict();
(function( $ ) {
console.log($.now(), jQuery.now())
})(jQuery);
};switchClassHour();
Hope this helps
function switchClassHour(){
if(document.getElementById('jq')){
//original switchClassHour() code.
}
else{
var jq = document.createElement('script');
jq.src = "WHATEVER SOURCE YOU WANT TO LOAD FROM (PROBABLY GOOGLE)";
jq.id = "jq";
document.getElementsByTagName('head').item(0).appendNode(jq);
//Original switchClassHour() code
}
}
I don't know if this is guaranteed to work since I don't know if you'll be able to load jQuery fast enough to call your function immediately afterwards. If this doesn't work because jQuery isn't loading fast enough then the only outcome I could see is adding a delay but that's ugly. To be honest if you're using jQuery I would just load it from Google normally in the <head> of your page. Most people have it cached already.
For a project i'm dynamically loading content that consist of html and javascript. Until now i was using jquery 1.8.3 but while cleaning up i wanted to update to 1.10.1.
I've narrowed my problem down to the way i use the $.html() function on my content div.
In jquery 1.8.3:
var content = $("#content");
contentDiv.html("<script> alert('Testing'); </script>")
shows a alertbox with the content 'Testing', while in newer jquery versions the same code the string is inserted into the DOM and then the alertbox also appears. I'd wish to not have the tags shown.
context javascript:
this.loadPage = function(page, callback){
$.get(page.ViewFile, function(view){
var content = $("#content");
$("#content").html(view);
}};
The page getting loaded contains, which is stored in the variable view as a string.
<h1>New Content</h1>
<div id="newContent"></div>
<script>
function View(){
this.InitializeView = function(model){
//code
}
this.UpdateView = function (model){
//code
}
}
</script>
Seems that the browser detect the </script> (the end of script tag) that is inside of string as a real closing when we put our code in the head of page.
This is the reason why the error is thrown in the webpage (EXAMPLE):
Uncaught SyntaxError: Unexpected token ILLEGAL fiddle.jshell.net/:22
I guess that you have to move your javascript code into a separate file like main.js, for example.
Tested it locally and it works:
HTML
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.js"></script>
<script src="main.js"></script>
<script type="text/javascript">
setTimeout(function () {
$("body").text("Testing now from HTML: using <script>");
setTimeout(function () {
$("body").html("<script>alert('This alert will fail.')</script>");
}, 1000);
}, 2000);
</script>
</head>
<body></body>
</html>
Javascript (main.js)
$(document).ready(function () {
$("body").html("<h1>Wait one second.</h1>");
setTimeout(function () {
$("body").html("<script>alert('Tested')</script>");
}, 1000);
});
Even the text editors detect it as closing tag:
Solution
1. Create scripts from jQuery
var content = $("#content");
var script = $("<script>");
script.html("alert('Testing');");
content.append(script)
1. Use &
Basically you have to replace < with <, > with > and & with &, as described in this answer:
var tagsToReplace = {
'&': '&',
'<': '<',
'>': '>'
};
function replaceTag(tag) {
return tagsToReplace[tag] || tag;
}
function safe_tags_replace(str) {
return str.replace(/[&<>]/g, replaceTag);
}
For more information see this question.