So I'm trying to clean up my code and currently the following scripts are in my HTML header
<script type="text/javascript" src="js/mobile.js"></script>
<script type="text/javascript">
$(document).ready(function(){
TriggerClick2 = 0;
$("#hamburger").click(function(){
if(TriggerClick2==0){
TriggerClick2=1;
$("#navi").animate({width:'35%'}, 1000);
}else{
TriggerClick2=0;
$("#navi").animate({width:'0%'}, 1000);
};
});
});
</script>
<script type="text/javascript">
$(document).ready(function(){
TriggerClick = 0;
$("#hamburger").click(function(){
if(TriggerClick==0){
TriggerClick=1;
$(".content").animate({width:'65%'}, 1000);
}else{
TriggerClick=0;
$(".content").animate({width:'100%'}, 1000);
};
});
});
</script>
<script type="text/javascript">
$(document).ready(function(){
$(".stayThere").mouseenter(function() {
$('.moveThere').animate({'margin-left': '0%'}, 1000);
}).mouseout(function() {
$('.moveThere').animate({'margin-left': '-100%'}, 1000);
});
});
</script>
I understand that this is quite redundant but I'm a beginner and am still learning. What I'm trying to do is move this code to the mobile/js linked at the very top of the code.
What I have inside the mobile.js right now looks as follows
//initializes each function.
function init() {
hideMenu();
scaleContent();
linkAnim1();
linkAnim2();
linkAnim3();
linkAnim4();
linkAnim5();
}
function hideMenu(){
TriggerClick2 = 0;
document.getElementById("hamburger").click(function(){
if(TriggerClick2==0){
TriggerClick2=1;
document.getElementById("navi").animate({width:'35%'}, 1000);
}else{
TriggerClick2=0;
document.getElementById("navi").animate({width:'0%'}, 1000);
};
});
};
function scaleContent(){
TriggerClick = 0;
document.getElementById("hamburger").click(function(){
if(TriggerClick==0){
TriggerClick=1;
document.getElementsByClassName("content").animate({width:'65%'}, 1000);
}else{
TriggerClick=0;
document.getElementsByClassName("content").animate({width:'100%'}, 1000);
};
});
};
function linkAnim1(){
document.getElementsByClassName("stayThere").mouseenter(function() {
document.getElementsByClassName('moveThere').animate({'margin-left': '0%'}, 1000);
}).mouseout(function() {
document.getElementsByClassName('moveThere').animate({'margin-left': '-100%'}, 1000);
});
};
//initializes the js functions above
window.onload = init;
sadly the moment I comment it out of the html document it stops doing anything altogether. To explain the functions, the first two are for mobile, bringing in the navigation while resizing the content, the other 5 are for each link Hover to animate a background image.
I'd really appreciate if someone could help me with this as I need it for January 4th, until which my teachers are unavailable.
Thanks again and happy coding
Ok I going to help you the best I can with out doing all of the work for you.
To begin you need only one document ready function for your script.
So take all of the JavaScript Code inside of the document ready functions and place it inside of a single document ready function.
Once you do that link to the JavaScript file by using the script tag right before your closing </body> tag in your html file.
Example(link to external JavaScript File):
<script src="myjavascriptfile.js"></script>
Note: The html code below assumes that your html file is in the same directory as the JavaScript.
Example(External JavaScript File Content):
$(document).ready(function(){//begin document closure
TriggerClick2 = 0;
$("#hamburger").click(function(){
if(TriggerClick2==0){
TriggerClick2=1;
$("#navi").animate({width:'35%'}, 1000);
}else{
TriggerClick2=0;
$("#navi").animate({width:'0%'}, 1000);
};
});
TriggerClick = 0;
$("#hamburger").click(function(){
if(TriggerClick==0){
TriggerClick=1;
$(".content").animate({width:'65%'}, 1000);
}else{
TriggerClick=0;
$(".content").animate({width:'100%'}, 1000);
};
});
$(".stayThere").mouseenter(function() {
$('.moveThere').animate({'margin-left': '0%'}, 1000);
}).mouseout(function() {
$('.moveThere').animate({'margin-left': '-100%'}, 1000);
});
});//end document closure
Now with that being said there is a lot of things that may be going wrong with your code. Posting your markup(HTML) will help with troubleshooting.
You are using global variables for your TriggerClick2, and TriggerClick one variables. Prefix them using the var keyword and place them at the top of the script inside of the document ready function.
You should try and get in the habit of using === instead of ==. Using === evaluates to exactly equals(matches value and type) where == matches the value. So if you want to make sure your matches the value and the variable type(number and string for example) then use === to prevent any potential headaches in the future.
Example:
var TriggerClick2 = 0;
var TriggerClick = 0;
Keep in mind that variables are scoped at the function level in JavaScript. So any variable that is declared inside of a function can not be accessed outside of the function it is declared in unless it returned by called a function that returns that variables value.
Related
I'm making a chat with the simple javascript:
<script>
function chatClick(messages_other_user) {
$('#chatBox').remove();
document.body.innerHTML += "<div id='chatBox' class='chatDiv'></div>";
$("#chatBox").load("subs/chat/chat.php?ou="+messages_other_user);
}
</script>
This function is called in several links with the variable "messages_other_user" changing.
In the file "chat.php" I get the variable of "ou" and I have a script that writes to the console:
if (isset($_GET['ou'])) { $otherUserChat = $_GET['ou']; } else $otherUserChat = 0; // get $otherUserChat
<script>
$(document).ready(function() {
var chatUpdateVar = setInterval(function() {
console.log("<?= $otherUserChat ?>");
}, 2000);
$.ajaxSetup({ cache: false });
});
</script>
But the .remove line doesn't quite get rid of the javascript in the chat.php file. When I click a link to call the javascript chatClick function, it works fine. But when I then click another link that calls chatClick with a different variable for "messages_other_user" the old one keeps firing along with the new one.
How can I destroy the old javascript completely so it doesn't run anymore?
I found the solution - and I was mistaken by the true culprit of the issue.
I thought a console.log would yield the same result as what I truly do - I just chose to replace with console.log in the code for simplicity. So I guess I've learned that's a stupid thing to do.
What is actually happening in the chat.php file in the document ready script is this:
$(document).ready(function() {
var chatUpdateVar = setInterval(function() {
$("#chatArea").load("subs/chat/chatContent.php?ou="+<?= $otherUserChat ?>);
console.log("updated");
}, 4000);
});
I figured out I didn't readlly need to use the document ready, so I instead, I just do this directly in my script:
var chatUpdateVar = setInterval(function() {
$("#chatArea").load("subs/chat/chatContent.php?ou="+<?= $otherUserChat ?>);
console.log("updated");
}, 4000); // CHECK FOR UNREAD: 1000 equals 1 second
$.ajaxSetup({ cache: false });
For closing the chat window, I now trigger this function:
function closeChat() {
clearInterval(chatUpdateVar);
$('#chatBox').remove();
}
And in the file that calls the above script (chat.php), I check if the function closeChat exists - and if it does, I run it. This is part of the cal to the chat.php:
function chatClick(messages_other_user) {
if (typeof closeChat === "function") {
closeChat();
}
document.body.innerHTML += "<div id='chatBox' class='chatDiv'></div>";
$("#chatBox").load("subs/chat/chat.php?ou="+messages_other_user);
}
Would you please help me delay execution of my function until the content has loaded? I've streamlined my code to the essentials, bear with my typos:
function Phase1()
{
$(".Hidden").load("hidden.html");
$(window).load(Phase2());
/* I've also tried $(document).ready(Phase2()); */
/* and $(."Hidden").load("hidden.html",Phase2()); */
/* and window.onload... */
}
function Phase2()
{
var Loop;
var Source_Array = document.getElementsByClassName("Random");
for (Loop=0;Loop<Source_Array.length,Loop++)
{ alert(Source_Array[Loop].innerHTML; };
}
The Random class contains several items. On the first pass the alerts are never called (length is 0), on the 2nd iteration it's had time to load everything.
I see no errors in the console when executing.
I have a small and neat solution for your problem, all you need to do is,
Call a setInterval for very short span to check the element is present in DOM or not, if its not your interval will go on, once the element is present, trigger your functions and clear that interval.
code will look like this..
var storeTimeInterval = setInterval(function() {
if (jQuery('.yourClass').length > 0) {
//do your stuff here..... and then clear the interval in next line
clearInterval(storeTimeInterval);
}
}, 100);
The page will load the elements from top to bottom.
If you want your JS code to execute after all elements have loaded, you may try any of the following:
Move your script to the bottom of the page.
<html>
<head></head>
<body>
<!-- Your HTML elements here -->
<script>
// Declaring your functions
function Phase1()
{
$(".Hidden").load("hidden.html");
}
function Phase2()
{
var Loop;
var Source_Array = document.getElementsByClassName("Random");
for (Loop=0;Loop<Source_Array.length,Loop++)
{ alert(Source_Array[Loop].innerHTML; };
}
// Executing your functions in that order.
Phase1();
Phase2();
</script>
</body>
</html>
Bind your functions to document ready using Vanilla JS.
document.addEventListener("DOMContentLoaded", function() {
Phase1();
Phase2();
});
Bind your functions to document using jQuery.
$(document).ready(function() {
Phase1();
Phase2();
});
I have below code that I have written in JavaScript and the script is referenced on the webpage. When the page loads, a call JavaScript happens and the logic's action should be rendered on the webpage.
Right now the script is firing on the webpage, but the action is not getting rendered on the webpage. However, if I execute the script on page console, changes happen.
<script>
function bannerLoad() {
var delayAddOn = setInterval(function() {
if ($(".add-ons").hasClass("current")) {
if ($('.addons-sidebar.clearfix img').length < 1) {
$(".addons-container :last").append($('<img>', {
class: 'img-responsive',
src: 'https://www.abc.in/content/dam/abc/6e-website/banner/target/2018/06/abc.png'
}));
}
clearInterval(delayAddOn);
}
}, 100);
};
window.onload = function() {
bannerLoad();
};
window.onclick = function() {
bannerLoad();
};
</script>
Can anyone check if there is any issue?
You need to call the script when the page is fully loaded, else the function will be called and can't find the DOM elements.
You should wrap your code inside the ready function:
<script>
//OPEN THE READY FUNCTION
$(function(){
bannerLoad(); //Call of your function when the page is fully loaded
$(window).click(bannerLoad);
});
//CLOSE THE READY FUNCTION
function bannerLoad() {
var delayAddOn = setInterval(function()
{
if($(".add-ons").hasClass("current"))
{
if($('.addons-sidebar.clearfix img').length < 1)
{
$(".addons-container :last").append($('<img>',{class:'img-responsive',src:'https://www.abc.in/content/dam/abc/6e-website/banner/target/2018/06/abc.png'}));
}
clearInterval(delayAddOn);
}
}, 100);
};
</script>
A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute. Code included inside $( window ).on( "load", function() { ... }) will run once the entire page , not just the DOM, is ready.
// A $( document ).ready() block.
$( document ).ready(function() {
console.log( "ready!" );
bannerLoad();
$(window).click(bannerLoad);
});
function bannerLoad() {
if($(".add-ons").hasClass("current"))
{
if($('.addons-sidebar.clearfix img').length < 1)
{
$(".addons-container :last").append($('<img>',{class:'img-responsive',src:'https://www.abc.in/content/dam/abc/6e-website/banner/target/2018/06/abc.png'}));
}
clearInterval(delayAddOn);
}
}, 100);
};
Your script has some little issues. I will try to evaluate them.
As bannerLoad is a function you don't need a ; at the end. Not an issue, just a hint.
As told before, bannerLoad is a function. So why would you wrap the function again in a function for your events? Just pass the function name directly, like window.click = bannerLoad;. Note that there are no bracers at the end, you just pass the name.
You function will always create a new delayAddOn variable with a new interval. So every time you click, another interval will be started and run in background. If you will do it like this, you need to put the variable on the outside of your function, to keep only one interval running at a time.
There is nothing wrong with using onload instead of a ready state from jQuery. But this belongs to you page setup and what you do. It would be more safe to rely on a ready state here, as told by others before. Because you already have a function, you could use it directly by $(bannerLoad);.
var delayAddOn;
function bannerLoad() {
delayAddOn = setInterval(function() {
if ($('.add-ons').hasClass('current')) {
if ($('.addons-sidebar.clearfix img').length < 1) {
$('.addons-container :last').append($('<img>', {
class: 'img-responsive',
src: 'https://www.abc.in/content/dam/abc/6e-website/banner/target/2018/06/abc.png'
}));
}
clearInterval(delayAddOn);
}
}, 100);
}
$(bannerLoad);
window.onclick = bannerLoad;
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>
I'm in a bit of a bind. I've been searching for a way to scroll smoothly through divs and found this fiddle:
http://jsfiddle.net/Vk7gB/187/
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://trevordavis.net/play/jquery-one-page-nav/jquery.scrollTo.js"></script>
<script type="text/javascript" src="http://trevordavis.net/play/jquery-one-page-nav/jquery.nav.min.js"></script>
<script type="text/javascript" src="http://mottie.github.io/Keyboard/js/jquery.mousewheel.js"></script>
<script type="text/javascript" src="scroll.js"></script>
The problem is that, while it works perfectly on the jsfiddle site, when i copy it exactly the same, without any changes, it stops working for some reason.
I've triple checked all external scripts and yet I can't find out what is the problem.
Here's the exact same code, copied directly from the fiddle and it does not work.
http://www.zero-blade.com/work/test2/
If anyone can point me in the right direction, I would greatly appreciate it.
Because in jsFiddle, the code runs inside the DOMReady event (look at the drop down under the jQuery version in the fiddle).
Wrap all your code inside
$(function(){
// you code here
});
You refer in your code to DOM elements, but they are not ready yet. Put all your <script> tags just before closing </body> tag.
The JavaScript in the fiddle is configured to execute when the DOM is ready. The JavaScript in your site (scroll.js) is being inserted and executed in the HEAD of your document, before the DOM elements exist, so no bindings are occurring.
All of your JavaScript should be at the end of the body, and moving scroll.js to the end of the body will solve the issue.
If you can't move the link to scroll.js, you can use jQuery's document.ready() in scroll.js to trigger the bindings to occur AFTER the DOM is ready, as follows:
scroll.js
var $current, flag = false;
$(function() {
// This code will be executed when the DOM is ready.
// This is a short version of $(document).ready(){...}
$('#nav').onePageNav();
$('body').mousewheel(function(event, delta) {
if (flag) { return false; }
$current = $('div.current');
if (delta > 0) {
$prev = $current.prev();
if ($prev.length) {
flag = true;
$('body').scrollTo($prev, 1000, {
onAfter : function(){
flag = false;
}
});
$current.removeClass('current');
$prev.addClass('current');
}
} else {
$next = $current.next();
if ($next.length) {
flag = true;
$('body').scrollTo($next, 1000, {
onAfter : function(){
flag = false;
}
});
$current.removeClass('current');
$next.addClass('current');
}
}
event.preventDefault();
});
});