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.
Related
I tried this:
<script src="js/jQuery.js"type="text/JavaScript"></script>
Then I tried to call a click function on my button:
<script>
$(document).ready(function (){
function jfn1(){
$("jbtn").fadetoggle()
}
})
</script>
Welcome to StackOverflow, Chisom.
All you did was define that function, you didn't actually call it. Also it needs to be "fadeToggle", not "fadetoggle".
/**
* Define function to fade button in/out
*/
function jfn1 () {
$("jbtn").fadeToggle() // "fadeToggle", not "fadetoggle"
}
/**
* On document ready (DOM loaded)
*/
$(document).ready(function (){
// Call function on document ready
jfn1()
})
This will call "fadeToggle" when the DOM tree is loaded. If you want to call it when clicked, it needs to look like this:
/**
* On document ready (DOM loaded)
*/
$(document).ready(function (){
// On button clicked
$("jbtn").click(function () {
// "this" is the function context
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
$(this).fadeToggle()
});
})
Also $("jbtn") will only find HTML elements that look like this: <jtbn>...</jtbn>. If you want to refer to a class (<HTML_ELEMENT class="jtbn"></HTML_ELEMENT>...), you should prefix it with a dot like this: $(".jbtn").
Good luck! 😊
I'm not sure what you're trying to achieve but with the code below, clicking on the button with class 'jbtn' will make it fade out.
$(document).ready(function (){
$('.jbtn').click(function() {
$( this ).fadeToggle();
});
})
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<button class="jbtn">Hey!</button>
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>
}
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>
Typically, you don't start querying the DOM until the $(document).ready().
In both of the options below, the Widget is declared (and the elements are queried) outside of the $(document).ready().
Is this OK? Can I initialize the jQuery elements (as long as I'm not manipulating anything), OUTSIDE of the ready handler?
Would it be better to put this whole Widget definition inside the $(document).ready()?
Should I wait until the Widget.init() to query the elements?
Note: I'm brand new to JS design patterns, so please note if I'm missing something
Option1
Widget = {
ele : $('#ele'),
init : function(){ ... }
};
$(document).ready(function(){
Widget.init();
});
Option2
Widget = (function(){
var privateEle = $('#privateEle');
return {
publicEle: $('#publicEle'),
init: function(){ ... }
};
}());
$(document).ready(function(){
Widget.init();
});
What I would do:
var Widget = (function(){
var ele;
function init(_ele){
ele = _ele;
};
return {
init: init
};
})();
$(function(){
Widget.init( $('#foo') );
});
If your script is loaded before jquery, you will not see an error "undefined is not a function". But, if you perform a query before domReady, you could get unexpected result, ele = []
EDIT: btw.. put your <script> tags before </body> NOT within <head></head>
It won't work because at the time when you query the element, the element is not there yet, thus your query will return an empty jQuery selection. You can only query for elements when the DOM is ready.
what would work though is on of the following:
create the element outside $(document).ready(). note that you have to provide the full html or work with $(..).attr(x,y) and the likes.
Widget = {
ele : $("<div id='ele'>"),
....
}
or you can query the element on widget initialization.
Widget = {
ele : "#ele",
init : function(){
this.ele = $(this.ele);
...
}
}
You can include script just before body end tag.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Demo</title>
</head>
<body>
<!-- my HTML -->
<script src="../js/vendor/jquery-1.9.1.js"></script>
<script src="../js/vendor/jquery-migrate-1.1.1.js"></script>
<script src="../js/custom.js"></script>
</body>
</html>
DOM is ready (no need for $(document).ready):
/*custom.js */
var Widget = (function($){
var _$element;
return {
init: function(){
_$element = $('#myElementId');
// TODO - element is available from now on
};
};
}(jQuery));
Widget.init();
I need to handle 'tweet' event. That is what I have now, but it doesn't work:
<script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>
<script type="text/javascript">
function jsTweet() {
// some other stuf here
// ...
var urlTW = "https://twitter.com/intent/tweet?text=Text&url=http://my_url.com";
var winTW = window.open(urlTW,'','toolbar=0, status=0, width=650, height=360');
}
(function() {
twttr.events.bind('tweet', function(event) {
alert('tweet!!!!');
});
}());
</script>
<a href="javascript:void(0)" onClick="jsTweet();">
Several things :
1/ Close your anchor tag.
2/ Your anonymous function is called only when the page is loaded. The twttr object doesn't exist at this time. So there is no binding done. Debug your function with Firebug or something, this should appear as an error.