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>
}
saying $ not defined, object expected.. actually i want to verify if all set of radio button check when a button is clicked! help plz
<script type="text/javascript">
$(document).on('click', 'form', function () {
var validate = true;
var unanswered = new Array();
// Loop through available sets
$('.qselections').each(function () {
// Question text
var question = $(this).prev().text();
// Validate
if (!$(this).find('input').is(':checked')) {
// Didn't validate ... dispaly alert or do something
unanswered.push(question);
validate = false;
}
});
if (unanswered.length > 0) {
msg = "Please answer the following questions:\n" + unanswered.join('\n');
alert(msg);
}
return validate;
});
</script>
Did you forget to include the jquery.js file in your markup before your code?
A generally accepted way to set up your script references is as follows (there are others, this isn't the be-all-end-all):
<html>
<head>
</head>
<body>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="MyScriptFile.js"></script>
<script>
$(function() {
$(document).on('click', 'form', function () {
var validate = true;
var unanswered = new Array();
// Loop through available sets
$('.qselections').each(function () {
// Question text
var question = $(this).prev().text();
// Validate
if (!$(this).find('input').is(':checked')) {
// Didn't validate ... dispaly alert or do something
unanswered.push(question);
validate = false;
}
});
if (unanswered.length > 0) {
msg = "Please answer the following questions:\n" + unanswered.join('\n');
alert(msg);
}
return validate;
});
</script>
</body>
</html>
This way you can be sure that (1) your page is loaded before any scripts try to do scripty things and (2) you have included jQuery before other scripts which may want to use it.
This is not foolproof, and you may (eventually) need to use something like Require.js or as a simpler step the defer attribute.
1.Have you included Jquery lib in first script tag in your head section. In that case only your jquery based code will execute.
2.Did you wrap the code into $(document).ready() function.
3 Are you using PHP at your corners. So need to replace $ with Jquery.
I am implementing the NicEdit editor with our own rich textbox ASP.NET control, which is just composite control that includes a TextArea and registers the NicEdit scripts on document ready.
The rich textbox control (and all our pages/controls) are also using JQuery.
The problem is that for some reason a piece of the NicEdit code's nulls out the "$" JQuery alias.
The following line of code executes when the control is loading:
onDomLoaded: function (A) {
debugger;
this.domLoad.push(A);
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", bkLib.domLoaded, null)
}
else {
if (bkLib.isMSIE) {
document.write("<style>.nicEdit-main p { margin: 0; }</style><script id=__ie_onload defer "+((location.protocol=="https:")?"src='javascript:void(0)'":"src=//0")+"><\/script>");
$BK("__ie_onload").onreadystatechange = function () {
if (this.readyState == "complete") {
bkLib.domLoaded()
}
}
}
} window.onload = bkLib.domLoaded
}
The specific line of code I am talking about is:
document.write("<style>.nicEdit-main p { margin: 0; }</style><script id=__ie_onload defer "+((location.protocol=="https:")?"src='javascript:void(0)'":"src=//0")+"><\/script>");
Before this executes, the $ alias points to JQuery, after the execution of that line, it is undefined.
I cannot seem to figure out what this line is suppose to do and why does it mess with the $ JQuery alias.
Could anyone suggest what is going on here?
Seems like the onDomLoaded function does not work good, so I used JQuery $(document).ready()
Before:
$(document).ready(function () {
bkLib.onDomLoaded(function() { new nicEditor().panelInstance('area1'); });
});
After:
$(document).ready(function () {
new nicEditor().panelInstance('id');
});
I have in a javascript file code, but it isn't encapsulate in a function, specifically is an event, so I need to know how can I call this event in my html file.
$(window).scroll(function() {
if ($(window).scrollTop() > 164) {
$("ticky-nav").show();
}
else {
$("ticky-nav").hide();
}
});
and I include that like this
<script type="text/javascript" src="static/js/GD.js"></script>
Thanks for your answers
You need to make sure it is either encapsulated in a $(document).ready() handler or after the DOM has loaded
$(document).ready(function () {
$(window).scroll(function () {
if ($(window).scrollTop() > 164) {
$("ticky-nav").show();
} else {
$("ticky-nav").hide();
}
});
});
$("ticky-nav") is an invalid selector also since there is no element type of ticky-nav you are most likely looking for $("#ticky-nav") which is an element with id ticky-nav
Also make sure to include
<script type="text/javascript" src="static/js/GD.js"></script>
underneath your jQuery script tag
If you want to execute the function without the scroll event, you can create it like this:
var doScroll = function() {
if ($(window).scrollTop() > 164) {
$("ticky-nav").show();
}
else {
$("ticky-nav").hide();
}
};
And then call doScroll(); from somewhere :)
I have a form which is submitted remotely when the various elements change. On a search field in particular I'm using a keyup to detect when the text in the field changes. The problem with this is that when someone types "chicken" then the form is submitted seven times, with only the last one counting.
What would be better is something like this
keyup detected - start waiting (for one second)
another keyup detected - restart waiting time
waiting finishes - get value and submit form
before I go off and code my own version of this (I'm really a backend guy with only a little js, I use jQuery for everything), is there already an existing solution to this? It seems like it would be a common requirement. A jQuery plugin maybe? If not, what's the simplest and best way to code this?
UPDATE - current code added for Dan (below)
Dan - this may be relevant. One of the jQuery plugins I'm using on the page (tablesorter) requires this file - "tablesorter/jquery-latest.js", which, if included, leads to the same error with your code as before:
jQuery("input#search").data("timeout", null) is undefined
http‍://192.168.0.234/javascripts/main.js?1264084467
Line 11
Maybe there's some sort of conflict between different jQuery definitions? (or something)
$(document).ready(function() {
//initiate the shadowbox player
// Shadowbox.init({
// players: ['html', 'iframe']
// });
});
jQuery(function(){
jQuery('input#search')
.data('timeout', null)
.keyup(function(){
jQuery(this).data('timeout', setTimeout(function(){
var mytext = jQuery('input#search').val();
submitQuizForm();
jQuery('input#search').next().html(mytext);
}, 2000)
)
.keydown(function(){
clearTimeout(jQuery(this).data('timeout'));
});
});
});
function submitQuizForm(){
form = jQuery("#searchQuizzes");
jQuery.ajax({
async:true,
data:jQuery.param(form.serializeArray()),
dataType:'script',
type:'get',
url:'/millionaire/millionaire_quizzes',
success: function(msg){
// $("#chooseQuizMainTable").trigger("update");
}
});
return true;
}
Sorry i haven't tested this and it's a bit off the top of my head, but something along these lines should hopefully do the trick. Change the 2000 to however many milliseconds you need between server posts
<input type="text" id="mytextbox" style="border: 1px solid" />
<span></span>
<script language="javascript" type="text/javascript">
jQuery(function(){
jQuery('#mytextbox')
.data('timeout', null)
.keyup(function(){
clearTimeout(jQuery(this).data('timeout'));
jQuery(this).data('timeout', setTimeout(submitQuizForm, 2000));
});
});
</script>
Here's your fancy jquery extension:
(function($){
$.widget("ui.onDelayedKeyup", {
_init : function() {
var self = this;
$(this.element).keyup(function() {
if(typeof(window['inputTimeout']) != "undefined"){
window.clearTimeout(inputTimeout);
}
var handler = self.options.handler;
window['inputTimeout'] = window.setTimeout(function() {
handler.call(self.element) }, self.options.delay);
});
},
options: {
handler: $.noop(),
delay: 500
}
});
})(jQuery);
Use it like so:
$("input.filterField").onDelayedKeyup({
handler: function() {
if ($.trim($(this).val()).length > 0) {
//reload my data store using the filter string.
}
}
});
Does a half-second delay by default.
As an update, i ended up with this which seems to work well:
function afterDelayedKeyup(selector, action, delay){
jQuery(selector).keyup(function(){
if(typeof(window['inputTimeout']) != "undefined"){
clearTimeout(inputTimeout);
}
inputTimeout = setTimeout(action, delay);
});
}
I then call this from the page in question's document.ready block with
afterDelayedKeyup('input#search',"submitQuizForm()",500)
What would be nice would be to make a new jquery event which uses this logic, eg .delayedKeyup to go alongside .keyup, so i could just say something like this for an individual page's document.ready block.
jQuery('input#search').delayedKeyup(function(){
submitQuizForm();
});
But, i don't know how to customise jquery in this way. That's a nice homework task though.
Nice job, Max, that was very helpful to me! I've made a slight improvement to your function by making it more general:
function afterDelayedEvent(eventtype, selector, action, delay) {
$(selector).bind(eventtype, function() {
if (typeof(window['inputTimeout']) != "undefined") {
clearTimeout(inputTimeout);
}
inputTimeout = setTimeout(action, delay);
});
}
This way you can use it for any type of event, although keyup is probably the most useful here.
I know this is old, but it was one of the first results when I was searching for how to do something like this so I though I would share my solution. I used a combination of the provided answers to get what I needed out of it.
I wanted a custom event that worked just like the existing jQuery events, and it needed to work with keypress + delete, backspace and enter.
Here's my jQuery plugin:
$.fn.typePause = function (dataObject, eventFunc)
{
if(typeof dataObject === 'function')
{
eventFunc = dataObject;
dataObject = {};
}
if(typeof dataObject.milliseconds === 'undefined')
dataObject.milliseconds = 500;
$(this).data('timeout', null)
.keypress(dataObject, function(e)
{
clearTimeout($(this).data('timeout'));
$(this).data('timeout', setTimeout($.proxy(eventFunc, this, e), dataObject.milliseconds));
})
.keyup(dataObject, function(e)
{
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 8 || code == 46 || code == 13)
$(this).triggerHandler('keypress',dataObject);
});
}
I used $.proxy() to preserve the context in the event, though there could be a better way to do this, performance-wise.
To use this plugin, just do:
$('#myElement').typePause(function(e){ /* do stuff */ });
or
$('#myElement').typePause({milliseconds: 500, [other data to pass to event]},function(e){ /* do stuff */ });