I have this function:
$(function ($) {
...
});
var getNotifyBar = $(".NotifyBar");
function showNotify(text) {
getNotifyBar.hide().find(".text").html(text).end().slideDown();
}
And when I use function showNotify(text) nothing happens. But when I put it in the JavaScript console (of the browser) it works.
More than likely this is running before all the elements with class NotifyBar are rendered
var getNotifyBar = $(".NotifyBar");
Which means that it is empty when you try to use it later. you should do this instead:
var getNotifyBar;
$(function ($) {
getNotifyBar = $(".NotifyBar");
});
Now it should be properly loaded. Next, you need to remember that getNotifyBar is a reference to a jQuery object already loaded from a selector. As such, you do not need to wrap it in $(). You should make this change:
function showNotify(text) {
getNotifyBar.hide().find(".text").html(text).end().slideDown();
}
Your code has no chance of working now and works from console, because when you run it in console it's after the DOMReady. Put the code in place of your 3 dots in the example and it will work, because:
$(function($){
//code here
})
will run the code after DOMReady
Related
can you help me?
I'm using a script in one file to call other function in another file, but I'm getting function is not defined. So I've start searching to fix this way but I didn't get any positive results. Check my code below:
index.html
$(document).ready(function(){
setInterval(function(){
lAs = new loadAsync();
}, 900);
});
js/plugins.js
function window.loadAsync() {
$(".loadAsync").each(function(index, element){
$(element).attr("src", $(element).attr("data-src"));
});
}
So, what should I do to fix this problem? Thank you.
#edit:
<script src="js/plugins.js"></script>
I've already wrote this in index.html
First, your syntax is wrong. An identifier may not have a . in it. Just use loadAsync and it'll be global unless you've nested it in another scope.
You can also make the jQuery more efficient by calling .attr() with a callback instead of using .each().
Finally, it seems unlikely that you actually want to use new to invoke the function. I changed the code below to simply pass it as the callback to setInterval. I also declared the lAs variable properly.
function loadAsync() {
$(".loadAsync").attr("src", function(){
return $(this).attr("data-src");
});
}
var lAs;
$(document).ready(function(){
lAs = setInterval(loadAsync, 900);
});
And of course all this can be done easily without jQuery.
function loadAsync() {
for (const el of document.querySelectorAll(".loadAsync")) {
el.src = el.dataset.src;
}
}
var lAs;
document.addEventListener("DOMContentLoaded", function(){
lAs = setInterval(loadAsync, 900);
});
First of all, function window.whatever() {} is wrong (could you include the link of the SO thread where you saw that being used ?).
Since you are getting an error even without that, please make sure that:
1. loadAsync is declared in the global scope in the plugins file.
2. You are including js/plugins.js correctly. Go on and insert foo bar; in js/plugins.js and then check if you get a SyntaxError (while including it before the other JS file), if you don't, you are not correctly including it.
I am creating the following code in JavaScript (inside file1.js)
function ABC () {
this.property01 = true;
}
ABC.prototype.doSomething = function () {
if (this.property01 == true) {
// Do something
}
}
Then later in a separate file in my project (lets call it file2.js), I have the following jQuery:
$(document).ready(function() {
var abc = new ABC();
// Some code here
abc.doSomething();
// continue with code
});
So far, everything is correct.
Now, what I would like to do is inside the prototype definition of doSomething() in file1.js, I want to use jQuery. Something along the lines
function ABC () {
this.property01 = true;
}
ABC.prototype.doSomething = function () {
if (this.property01 == true) {
$('#find-element'). .... // ... Do Something
}
}
But I am not sure how to do this. If I wrap the code of file1.js with a jQuery document-ready wrapper, then the line var abc = new ABC(); inside file2.js will throw an error because it no longer recognizes the function definition in file1.js.
Can I use jQuery inside a prototype the way I explained above? How can I do that? How can I structure my files to allow for this to happen?
This should work just fine just as long as jQuery has fully loaded before file1.js and file1.js have. If you explicitly load them in the correct order, the $ will be available globally, and the other files shouldn't have an issue recognizing that object. In fact, if you load things correctly, you shouldn't even need a document-ready setup to gain access to $.
<script src="../jquery.js"></script>
<script src="../file1.js"></script>
<script src="../file2.js"></script>
If, for some reason, you're having conflicts with the $ object, you could also just use the word jQuery to make your calls: jQuery('#find-something')
I want to execute a function which was defined in the start of the script, lets call this function initialize. This function also uses a variable, lets call it login, which is defined by a php file that includes my jquery script file after defining the variable login.
php/html:
<script type="text/javascript">
login = '<?php echo $login; ?>';
...
</script>
<!-- script is included -->
<script type="text/javascript" src="script.js"></script>
jquery:
function initialize(){
$("." + login).remove();
}
jQuery.moreContent = function moreContent()
{
//more content is loaded
...
initialize();
}
the moreContent function is then loaded, I can see more content appearing on my screen but initialiye is not loaded. only if I use a function like resize (in the end of the script.js file) it works
jquery (in the end of script):
//load function initialize
initialize();
//this function doesnt work too, I tested if it even loads and it does (used a number that was increased by one whenever function was loaded which actually happened...)
//however the wished element with the class of variable login is not removed
//resize function
$(window).resize(initialize);
//this one suddenly works
...
I have no idea why it suddenly works with the other function and why it doesnt work in the other cases
You need to wrap your code and make it run once the document is ready, like this:
$(document).ready (function(){
// run all your functions here
});
Maybe the variable login is empty in the other function, or you are giving thst a different value.
Try with a global variable to test it, like
window.login = script_php
And try again, in this ways, the login variable is global, or pass this variable as a parameter in the function.
the moreContent function is then loaded, I can see more content appearing on my screen but initialize is not loaded.
That is not exactly what happened. You have attached a function as method directly to jQuery object but did not invoke it,
jQuery.moreContent = function moreContent()
{
//more content is loaded
...
initialize();
}
You won't get any fruitful benefit from doing it this way. You have just added a method to an object (jQuery in this case) which is not invoked yet. In any case you do not need to add it as a method to jQuery object itself. You can do it easily without this as following.
function initialize(){
$("." + login).remove();
}
// this is a global function right now, use it anywhere you want.
function moreContent()
{
//more content is loaded
...
initialize();
}
// document ready...
$(function(){
moreContent();
});
You can rearrange the code and remove the unnecessary function layers (depends upon your code structure) and use it like this.
$(function(){
// more content...
initialize();
});
if I use a function like resize (in the end of the script.js file) it works
It worked because it is attached directly to window by jQuery on resize event.
$(window).resize(function(){
// The code inside will work whenever user resizes the window.
// It does not need to be hooked up inside document ready.
});
I have no idea why it suddenly works with the other function and why it doesnt work in the other cases
The reason it worked inside event handlers is because you hooked up your functions to run as a callback function to them. You have set it up correctly in click or resize event but not in load event. In load event you just created a function and added the it as a method to jQuery object but did not invoke it. The only and only way a function runs inside JavaScript is when you suffix parenthesis.
function demo()
{
// do something...
return "Done";
}
// a named function "demo" got created, but not invoked.
demo; // returns the whole function literal, not invoked yet.
demo(); // invoked, returns Done
So continuing from this, adding it as a method to jQuery will not load it, until you invoke it e.g.
jQuery.myNewMethod = function myNewMethod() {
return "Hey there :)";
}
// jQuery loaded, but where is my method ?? (#__#)
// let's invoke it then...
jQuery.myNewMethod(); // invoked the function using parenthesis!
// returns "Hey there :)"
// Now i can see you go (^__^)
I have a function which changes the width of some images. This happens when I hover over a different div in a different function. For some reason the the called function only performs some lines of code and then it stops.
function hey()
{
alert(0);
var $imgContent = ('.imgContent');
$imgContent.css("width","10%");
alert(2);
}
var $content = $('.content');
$content.mouseenter(function() {
$content.removeClass('full').addClass('partial');
$(this).addClass('full').removeClass('partial');
$(this).find('.img1').css('display','none');
$(this).find('.img2').css('display','');
if($(this).hasClass('cont1')){
alert(1);
hey();
}
if($(this).hasClass('cont2')){
}
if($(this).hasClass('cont3')){
}
if($(this).hasClass('cont4')){
}
}).mouseleave(function(){
$(this).find('.img1').css('display','');
$(this).find('.img2').css('display','none');
$(this).removeClass('full').addClass('partial');
});
In the mouseenter() function when I check if $(this).hasClass('cont1') then I perform an alert, which works. After that I call on function hey(). This is where my problem arises. After calling function hey() i perform another alert(0) , which also works. But the lines of code after that do not get executed and the last alert(2) doesn't work either.
There is an error in your code.
Replace:
var $imgContent = ('.imgContent');
With
var $imgContent = $('.imgContent');
You have a mistake in your jquery object definition.
Per jQuery():
jQuery() — which can also be written as $() — searches through the DOM for any elements that match the provided selector and creates a new jQuery object that references these elements
so in your case you should have:
var $imgContent = $('.imgContent');
$imgContent.css("width","10%");
Also, it's important to note that in your .mouseenter() function you refer to:
$content.removeClass('full').addClass('partial');
$(this).addClass('full').removeClass('partial');
$content and $(this) both refer to the same object, so in essence these lines are pointless.
I have this code in <script> tags at the top of my HTML file.
$(document).ready(function()
{
$('#scrollbar1').tinyscrollbar();
$('a.jqtree_common').click(updateScrollbar());
});
$(function updateScrollbar()
{
var oScrollbar = $('#scrollbar1');
oScrollbar.tinyscrollbar();
oScrollbar.tinyscrollbar_update();
$('a.jqtree_common').click(updateScrollbar());
});
But for some reason when I run this, it says updateScrollbar() is undefined within (document).ready. When I try to define updateScrollBar() inside of (document).ready then updateScrollBar() gets caught in some kind of endless loop.
My question is twofold:
What can I do to make updateScrollBar() defined within the scope of (document).ready?
Is there a better way to assign this function to the 'a.jqtree_common' elements? They are created dynamically at runtime, and modified as the webpage is used. I want the function to run every time one of them is clicked.
I'm using tiny scrollbar and jqtree
EDIT: I want the $('a.jqtree_common').click(updateScrollbar); assignment to be made every time the scrollbar is updated, since I believe clicking on a 'a.jqtree_common' element creates more 'a.jqtree_common' elements.
Pass the function reference as the callback, instead of the result of the function in Click event. () will invoke the function and set the result as a call back which inturn calls updatescrollbar inside it again and goes in an infinite loop.
$(document).ready(function()
{
$('#scrollbar1').tinyscrollbar();
$('a.jqtree_common').click(updateScrollbar);
});
function updateScrollbar()
{
var oScrollbar = $('#scrollbar1');
oScrollbar.tinyscrollbar();
oScrollbar.tinyscrollbar_update();
//$('a.jqtree_common').click(updateScrollbar);
}
Okay, I know there are a lot of hats in the ring at this point, but here's my entry just the same...
//IMMEDIATELY-INVOKED FUNCTION EXPRESSION (IIFE)
// Used for privacy/variable scoping
(function(){
//bind init function to dom-ready event
$(init); //same as $(document).ready(init);
//initialize event bindings for page
function init() {
//initialize scrollbar
$('#scrollbar1').tinyscrollbar();
//click binding for tree
$('a.jqtree_common').click(updateScrollbar);
//assuming you want to run the updateScrollbar on page load
//in addition to clicks
updateScrollbar();
}
//handles scrollbar updates
function updateScrollbar() {
//assuming the tinyscrollbar() initialization only needs
//to happen once, inside the initialization event.
$('#scrollbar1').tinyscrollbar_update();
}
}());
The structure above is pretty much how I work through things... I do my variables first, then event bindings at the top, and have my function declarations below. This works because of function hoisting (in compilation of the JS, function declarations are moved to the top), this doesn't work with function assignments (ex: var x = function(){...}), then I wrap the whole thing inside an IIFE. I find that this structure provides easier readability and comprehension. I don't like putting my bindings at the bottom, as I find you have to go over a lot to get to what you are looking for.
Try this code:
$(document).ready(function() {
var updateScrollbar = function () {
var oScrollbar = $('#scrollbar1');
oScrollbar.tinyscrollbar();
oScrollbar.tinyscrollbar_update();
};
$('#scrollbar1').tinyscrollbar();
$('a.jqtree_common').click(updateScrollbar).click();
});
To bind elements loaded later we must use this .on( function
$(document).ready(function(){
$('#scrollbar1').tinyscrollbar();
$(document).on("click","a.jqtree_common", updateScrollbar);
});
function updateScrollbar(){
var oScrollbar = $('#scrollbar1');
oScrollbar.tinyscrollbar();
oScrollbar.tinyscrollbar_update();
}
and if you want the scope limitation then declare function within the block
$(document).ready(function(){
$('#scrollbar1').tinyscrollbar();
$(document).on("click","a.jqtree_common", updateScrollbar);
function updateScrollbar(){
var oScrollbar = $('#scrollbar1');
oScrollbar.tinyscrollbar();
oScrollbar.tinyscrollbar_update();
}
});
This is what ultimately worked for me:
$(document).ready(function()
{
$('#scrollbar1').tinyscrollbar();
$('a.jqtree_common').click(updateScrollbar);
function updateScrollbar()
{
var oScrollbar = $('#scrollbar1');
oScrollbar.tinyscrollbar();
oScrollbar.tinyscrollbar_update();
$('a.jqtree_common').click(updateScrollbar);
}
});