A bunch of code isn't working and I'm trying to identify where the problem lies but console.log() isn't logging any results in Chrome Dev tools, am I doing it correctly?
$(window).scroll(function() {
$('section').each(function(){
var id='#'+$(this).attr('id'),
off=$(id).offset().top,
hei=$(id).height(),
winscroll=$(window).scrollTop(),
dif=hei+off-($(window).height());
if (winscroll >= off && winscroll<=dif) {
console.log('first broken');
$(id+' .sticky').removeClass('abs').addClass('fix');
} else if (winscroll > dif){
console.log('second broken');
$(id+' .sticky').removeClass('fix').addClass('abs');
} else {
console.log('third broken');
$(id+' .sticky').removeClass('fix abs');
} });
});
EDIT FULL CODE ADDED
$(document).ready(function() {
// If a browser supports 3D transforms use the fancy menu if it doesn't, use standard accordion menu instead
if($('html').hasClass('csstransforms3d')){
$( "#mp-menu" ).removeClass( "snap-drawers" ).addClass( "mp-menu" );
$('nav ul li ul').css('border-bottom','1px solid rgba(255, 255, 255, .05)');
$('nav ul li ul').css('background','none');
// Insert elements where necessary to create the right structure
$('#mp-menu').wrapInner('<div class="mp-level" />');
$('#mp-menu').find('li > ul').wrap('<div class="mp-level" />');
$("#mp-menu ul li .mp-level").prepend(function () {
return '<span class="menu-title">' + $(this).prev().text() + '</span> <a class="ico mp-back" href="#">Back</a>';
});
// load in necessary JS files
$.getScript('http://176.32.230.2/baodev.com/cjo/wp-content/themes/CJO/js/multi-level-menu.js');
} else {
// load in necessary JS files
$.getScript( "http://176.32.230.2/baodev.com/cjo/wp-content/themes/CJO/js/jquery.navgoco.min.js", function() {
$("#demo1").navgoco({accordion: true});
});
$.getScript( "http://176.32.230.2/baodev.com/cjo/wp-content/themes/CJO/js/snap.min.js", function() {
// Snapper settings
var snapper = new Snap({
element: document.getElementById('scroller'),
disable: 'right',
maxPosition: 291
});
var addEvent = function addEvent(element, eventName, func) {
if (element.addEventListener) {
return element.addEventListener(eventName, func, false);
} else if (element.attachEvent) {
return element.attachEvent("on" + eventName, func);
}
};
// Toggle button
addEvent(document.getElementById('trigger'), 'click', function(){
if( snapper.state().state=="left" ){
snapper.close();
$( ".menu-trigger" ).removeClass( "active" );
} else {
snapper.open('left');
$( ".menu-trigger" ).addClass( "active" );
}
});
addEvent(document.getElementById('scroller'), 'click', function(){
if( snapper.state().state=="left" ){
$( ".menu-trigger" ).removeClass( "active" );
}
});
/* Prevent Safari opening links when viewing as a Mobile App */
(function (a, b, c) {
if(c in b && b[c]) {
var d, e = a.location,
f = /^(a|html)$/i;
a.addEventListener("click", function (a) {
d = a.target;
while(!f.test(d.nodeName)) d = d.parentNode;
"href" in d && (d.href.indexOf("http") || ~d.href.indexOf(e.host)) && (a.preventDefault(), e.href = d.href)
}, !1)
}
})(document, window.navigator, "standalone");
});
} // end if
fitHeight();
$(window).scroll(function() {
$('section').each(function(){
var id='#'+$(this).attr('id'),
off=$(id).offset().top,
hei=$(id).height(),
winscroll=$(window).scrollTop(),
dif=hei+off-($(window).height());
console.log('msj');
if (winscroll >= off && winscroll<=dif) {
$(id+' .sticky').removeClass('abs').addClass('fix');
} else if (winscroll > dif){
$(id+' .sticky').removeClass('fix').addClass('abs');
} else {
$(id+' .sticky').removeClass('fix abs');
}
});
});
});
// Trigger FitHeight on browser resize
$(window).resize(fitHeight);
EDIT
Some bits of the full code (above) refer to other JS files and code returns no errors when run with these files present. After troubleshooting I see the console message before the scroll function but I do not see the console message within the scroll function.
fitHeight();
console.log('About to bind scroll effects'); // I SEE THIS MESSAGE
$(window).scroll(function() {
console.log("scroll bound, now loop through sections"); //BUT NOT THIS ONE
$('section').each(function(){
In my case, all console messages were not showing because I had left a string in the "filter" textbox.
Remove the filter it by clicking the X as shown:
Sounds like you've either hidden JavaScript logs or specified that you only want to see Errors or Warnings. Open Chrome's Developer Tools and go to the Console tab. At the bottom you want to ensure that JavaScript is ticked and also ensure that you have "All", "Logs" or "Debug" selected.
In the image above I have JavaScript, Network, Logging, CSS and Other ticked and "All" selected.
Another potential problem could be that your $(window).scroll() function isn't wrapped within a .ready() function (as documented here):
$(document).ready(function() {
$(window).scroll(function() {
...
});
});
When pasting your code into JSFiddle and giving some dummy content, your code works perfectly fine: JSFiddle demo.
Edit:
The question was edited. The new code given throws two errors:
Uncaught ReferenceError: fitHeight is not defined
Uncaught TypeError: Cannot read property 'addEventListener' of null
Because of this, the code stops execution prior to reaching any console.log call.
Click on the restore button. console.log will start to work.
I feel a bit stupid on this but let this be a lesson to everyone...Make sure you target the right selector!
Basically the console wasn't logging anything because this particular code snippet was attempting to grab the scrolling area of my window, when in fact my code was setup differently to scroll an entire DIV instead. As soon as I changed:
$(window).scroll(function() {
to this:
$('#scroller').scroll(function() {
The console started logging the correct messages.
It was because I had turned off "Logs" in the list of boxes earlier.
2021 solution
open developer tools
navigate to "console"
most likely "Verbose" is not ticked, so activate it
In my case I was developing a Polymer WebComponent, which is included using <link rel="import"> into the main HTML document. Turns out that the WebComponent HTML file was being cached for some reason, even though I had changed it since the cached version.
To solve it I opened the Developer Console (in Chrome), right clicked on the reload arrow next to the URL bar and selected "Empty cache and hard reload" - problem solved.
Somewhere console.log had been overridden in a js file somewhere (that I haven't been able to locate).
But I could test by putting console.log in the console and I only got an empty function: f{}
I added this to the top of my own js file to correct it (absolute hack, but worked for me):
var console = window.console;
Just you need to select right option to show the log messages from the option provided in left side under the console tab. You can refer the screen shot.
I just had a same issue of none of my console message showing. It was simply because I was using the new Edge (Chromium based) browser on Windows 10. It does not show my console messages whereas Chrome does. I guessed it was an issue with Edge because I had another odd issue with Edge because it treated strings with single quotes and double quotes differently.
Consider a more pragmatic approach to the question of "doing it correctly".
console.log("about to bind scroll fx");
$(window).scroll(function() {
console.log("scroll bound, loop through div's");
$('div').each(function(){
If both of those logs output correctly, then its likely the problem exists in your var declaration. To debug that, consider breaking it out into several lines:
var id='#'+$(this).attr('id');
console.log(id);
var off=$(id).offset().top;
var hei=$(id).height();
var winscroll=$(window).scrollTop();
var dif=hei+off-($(window).height());
By doing this, at least during debugging, you may find that the var id is undefined, causing errors throughout the rest of the code. Is it possible some of your div tags do not have id's?
As a complete new at javascript, I just had the same problem on my side here. The mistake I did, was that I used:
<script type="text.javascript">
console.log("bla bla bla");
</script>
instead of:
<script>
console.log("bla bla bla");
</script>
using the
type="text.javascript"
had the result of not producing the log in the console.
In my case it was caused by console.groupCollapsed().
And collapsed messages don't get detected by ctrl+f apparently.
Maintaining unfamiliar code is scary sometimes...
It even collapsed the exception message, absence of which made me put those console.logs in the first place ^_^
if using $ parameter in console.log within html, then single quotes(') and double quotes("") will not work.
use quotes like (` `)
example:
console.log(`${address}`);
This will help when using the $ parameter and anyone facing issues in console.log.
Related
I have this code here:
$(document).ready(function() {
debugger;
$("div[id^='stage_']").click(function (e) { alert('Hello'); });
});
The weird thing I can't explain is, that when I execute the selector once I'm in the console when reaching the debugger statement, it returns an empty array, []
But when I step out and go on the page, then hit Ctrl-Shift-C in Chrome to start inspecting and click on some of the div's that have the ID I'm looking for then execute the selector again in the console, now I have the elements I'm expecting.
I have even tried this here so to validate whether it was an async. loading issue (this is a system over which I don't have all the control). but still, when reaching the debugger, the selector doesn't work - even after waiting 10 seconds (which then I'm pretty sure the div's are there). I still have to go in inspector so jQuery recognize the elements.
$(document).ready(function() {
//debugger;
setTimeout(function() {
debugger;
$("div[id^='stage_']").click(function (e) { alert('allo'); });
}, 10000);
});
Why would jQuery only be aware of elements that I've clicked on with Chrome's inspector ?
I know it's a bit late but when you open Dev Tools in Chrome the execution context is set to top. If your controls are located within an iFrame, that is a different context, not accessible from top. Use the dropdown to select your iFrame's context and your jQuery will return an element.
The reason it works when you inspect an element, is Chrome has selected the execution context for you already.
Discussion about iFrame context in Dev Tools
Using the "on", it works even if the element exists after the page loads.
$(document).ready(function(){
//$("div[id^='stage_']").click( function (e) { alert('Hello'); });
$("body").on('click','div[id^="stage_"]', function (e) { alert('Hello'); });
$('body').html('<div id="stage_1">teste1</div>' +
'<div id="stage_2">teste2</div>' +
'<div>blabla</div>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
doc: http://api.jquery.com/on/
Several problems:
1) I am trying to make this script run more efficiently.
2) When the user clicks either pop out button it opens a windows and hides the element. (Currently I am using .detach() to remove the embedded video player because in Firefox .toggle() just hides the player but keeps the audio playing. Is there a better way to do this?
3) In theory by clicking the button again or closing the window manually it should un hide or .toggle() the element but does not for the video player due to detach().
4) If a user pops out the window manually closes it and then pops it out again to only close it once more the element does not .toggle() back.
See it in action here, http://www.mst3k.tv/.
$(document).ready(function() {
$('#lights').click(function(){$('#darkness').fadeToggle(500);});
$("#lights").toggle(function(){$("#lights").attr('id','lightsoff');},function(){$("#lightsoff").attr('id','lights');});
/**VIDEO**/
var videoWin;
$('#video-toggle').click(function(){
$('#video').fadeToggle(500);
$('#video').detach();
});
$('#video-toggle').click(function(){
if (videoWin && !videoWin.closed) {
videoWin.close();
return false;
}
videoWin = window.open(
$(this).attr('rel'),
'videoWin',
'width=600,height=480,toolbar=0,top=0,left=0,menubar=0,location=0,status=0,scrollbars=0,resizable=1');
return false;
}
);
var watchVideo = setInterval(function() {
if (videoWin.closed) {clearTimeout(watchVideo);$('#video').show(500)}
return false;
}, 1);
/**CHAT**/
var chatWin;
$('#chat-toggle').click(function(){
$('#chat').fadeToggle(500);
/*$('#chat').detach();*/
});
$('#chat-toggle').click(function(){
if (chatWin && !chatWin.closed) {
chatWin.close();
return false;
}
chatWin = window.open(
$(this).attr('rel'),
'chatWin',
'width=320,height=480,toolbar=0,top=0,left=601,menubar=0,location=0,status=0,scrollbars=0,resizable=1');
return false;
}
);
var watchChat = setInterval(function() {
if (chatWin.closed) {clearTimeout(watchChat);$('#chat').show(500)}
return false;
}, 1);
/*$("a.btn").fitText(1.2, { minFontSize: "6px", maxFontSize: "14px" });*/
});
It would be better if you created a jQuery plugin for your code so you can re-use it and avoid DRY. Here are a couple of options:
Plugin 1: jQuery popupWindow
Plugin 2: jQuery winPop
Also note that the closed property is not part of any W3C specification, however it might be supported across Browsers.
You could also write a JS function that could be reused. According to the w3cschools website the window.closed property is supported in most major browsers and you can check for it prior to triggering the event.
instead of
if(videoWin && !videoWin.closed)
you could use
if (typeof videoWin!='undefined'){ /* it has been created */}
elseif(typeof videoWin='undefined') { /*it's okay to open the new window*/}
Make sure you're not creating the variable if you're using this as a check though until the window open event has been fired. Since you're creating the var a couple of lines above your function declaration it will always return as defined.
You'll need to specify a target object in your function to have it throw multiple windows correctly... meaning you can't declare one var for multiple windows. Maybe a class would be better.
Something I thought was odd earlier but forgot to mention before FB posted my response prematurely was that you're adding your href in the rel attribute and specifying the href as a js:void(0) which is also non-standard. The rel attribute is for specifying the relationship between the link and the page... (eg. rel=nofollow). That might also be why it's not firing and misfiring some of the time as well, and the differences between browser response.
I am trying to create a "skip navigation" link without being able to use anchors. The site is built in a peculiar way, where anchor link formatting has been re-purposed. So, I am attempting to allow people to skip the navigation by using focus. However, it isn't working.
HTML code for the skip navigation link itself:
<!-- Start Top Left in Nav Bar -->
<aside>
Skip Navigation
</aside>
<!-- End Top Left in Nav Bar -->
Code to Change the Focus
var nav = document.getElementById('#skipNav');
nav.onclick=skipNav();
function skipNav(){
document.activeElement.blur();
if ($('#linkHome').hasClass('current')==true)
{
$('#homeFocus').focus();
}
if ($('#linkTeam').hasClass('current')==true)
{
$('#teamFocus').focus();
}
if ($('#linkTraining').hasClass('current')==true)
{
$('#trainingFocus').focus();
}
if ($('#linkTesting').hasClass('current')==true)
{
$('#testingFocus').focus();
}
if ($('#linkRemediation').hasClass('current')==true)
{
$('#remediationFocus').focus();
}
if ($('#linkContact').hasClass('current')==true)
{
$('#contactFocus').focus();
}
};
Script to Change Pages and Mark Current Page
var FluidNav = {
init: function() {
$('a[href*="#"]').click(function(e) {
e.preventDefault();
if($(this).attr("href").split("#")[1]) {
FluidNav.goTo($(this).attr("href").split("#")[1]);
}
});
this.goTo("home");
},
goTo: function(page) {
var next_page = $("#"+page);
var nav_item = $('nav ul li a[href=#'+page+']');
$("nav ul li").removeClass("current");
nav_item.parent().addClass("current");
FluidNav.resizePage((next_page.height() + 40), true, function() {
$(".page").removeClass("current"); next_page.addClass("current");
});
$(".page").fadeOut(500);
next_page.fadeIn(500);
document.activeElement.blur();
$('#'+page+'Focus').focus();
FluidNav.centerArrow(nav_item);
},
centerArrow: function(nav_item, animate) {
var left_margin = (nav_item.parent().position().left + nav_item.parent().width()) + 24 - (nav_item.parent().width() / 2);
if(animate != false) {
$("nav .arrow").animate({
left: left_margin - 8
}, 500, function() { $(this).show(); });
} else {
$("nav .arrow").css({ left: left_margin - 8 });
}
},
resizePage: function(size, animate, callback) {
if(size) { var new_size = size; } else { var new_size = $(".page.current").height() + 40; }
if(!callback) { callback = function(){}; }
if(animate) {
$("#pages").animate({ height: new_size }, 400, function() { callback.call(); });
} else {
$("#pages").css({ height: new_size });
}
}
};
$("nav select").change(function() {
if(this.options[this.selectedIndex].value != "#") {
var page = this.options[this.selectedIndex].value.split("#")[1];
FluidNav.goTo(page);
$("html,body").animate({ scrollTop:$('#'+page).offset().top }, 700);
}
});
Any ideas?
Sounds like you're trying to do a 'dynamic skiplink', where you determine the target at runtime?
Skip Navigation
The problem is that when you click a link, navigation happens. A href="" doesn't prevent navigation, it just means that you end up navigating to the current page - and that's going to reset the focus. This happens after your click event handler. So even though you may correctly set the focus where you want to, it ends up being 'lost' when the page reloads.
There's a couple of ways to prevent this: one is to use href="javascript:void(0)" - href specifies where to navigate, and if it evaluates to void, the browser won't navigate at all.
A somewhat cleaner way is to tell the browser not to carry out the default action in the event handler:
function skipNav(e)
{
e.preventDefault(); // prevent default action - link navigation - from taking place
...
--
Couple of other issues with the code:
Don't bother with role="link" on the A - save these attributes for when you are doing something out of the ordinary. The key thing to know is that screenreaders already know how to deal with all the standard HTML elements when they are used in a standard way. So if you are using an as a link, or a as a button, then you don't need to add a role.
But if you are creating a new control of of plain DIVs, or if you are repurposing a HTML element for a different use, then you need a role attribute to tell the screenreader how you are actually using the element.
For example, a DIV that's had an onclick handler and is behaving like a button would need role="button", otherwise a screenreader might ignore it or just say something generic like 'element'. Or if you are creating a button from an A tag, and it ends up behaving like and looking like a button from a user's point of view, then you'd need role="button" so that a screenreader will announce it as a button rather than as a link.
--
Watch for mixing plain DOM vs jQuery conventions - only jQuery uses # to find elements by ID, so use either:
var nav = document.getElementById('skipNav'); // plain DOM way, no #
or
var nav = $('#skipnav'); // jQuery way using selector
--
Watch for functions as values vs calls:
nav.onclick=skipNav();
This will actually call skipNav(), and assign the return value - null! - to onclick. Don't use ()'s when you're setting a callback. You don't need this code anyhow, since you're setting the handler using onClick in the tag anyhow.
Also, note that as your code stands, when skipNav() is called, it tries to call document.activeElement.blur() - but at that point in time - document is still loading - there's no activeElement, so calling blur() on null generates an exception - which you should see in your browser's console/debugging window.
--
Don't use .blur() - there's no need to do this:
document.activeElement.blur();
Instead, just focus the element you want to have focus. The danger with doing .blur() is that if the code after it fails to set the focus somewhere reasonable, focus will end up getting 'lost', which is very inconvenient for a keyboard user, since they have to tab from the start of the page.
--
Javascript coding practice: don't bother with == true in the if() expressions; and unless you expect you expect more than one of the elements to have the 'current' class, use else if instead of plain if: this makes it clear in the code that you're expecting only one branch to be used.
--
Finally, make friends with the browser's debugger (F12 in most): you'll learn some of the above by putting breakpoints in the event handler and your initialization code, and stepping through it to ensure it's behaving as you expect.
I have it so when you click on the elements such as the top right one hydrogen it plays a video in the big center div and displays info about hydrogen. I got it to work locally but i am unable to get it to work online.
Please any help would be great.
Here is the link to my project
http://travismichael.net/periodic_elements/
Here is the script for my site
<script type="text/javascript">
$(document).ready(function() {
$('div.video').hide();
$('.icon').click(function(){
var id=$(this).data('id'),
thisDiv=$("div.video[data-id='" + id +"']"),
thisVideo=$("div.video[data-id='" + id +"']").find('video');
$('video').each(function() {
this.pause();
this.currentTime = 0;
});
$('div.video').not(thisDiv).fadeOut('fast');
thisDiv.fadeIn();
thisVideo.get(0).play();
});
});
</script>
<script type="text/javascript">
$("#periodictable td").hover(function() {
$(this).stop().animate({opacity: "1"}, 'fast');
},
function() {
$(this).stop().animate({opacity: ".7"}, 'slow');
});
</script>
Error is here:
You're trying with
var thisDiv = ("div.video[data-id='" + id +"']");// but it returns jQuery object,
// not element
// Thats why below statement will not work
// because it works on element
alert(thisDiv.nodeType);
So you should try like this:
var thisDiv = ("div.video[data-id='" + id +"']")[0]; // returns the element
alert(thisDiv.nodeType); // and then get the nodeType
When checked I get an error message that says the Element is undefined.
you should past the error your console is giving you, as it is going to give much more explanation to what you are looking for.
It is obviously throwing an exception and whatever your exception is is displaying the error message, so...you try it on your local host where the files are defined. Are they declared in your code with a pointer or something to say go look back here and use this when the button is clicked?
It looks like your function should contain these declarations, or you could make them global, not really sure without more info...
I am currently trying to make some jQuery hover effects render correctly in all browsers. For the moment, firefox, IE, opera all do what they are supposed to. However, Safari and Chrome do not.
The code looks like this:
<div id="button1">
<div id="work_title" class="title_james">
WORDS
</div>
</div>
<div id="button2">
<div id="work_title" class="title_mike">
MORE WORDS
</div>
</div>
and the script effecting it looks like this
<script>
$(function() {
$("#button2").hover(
function() {
$("#james").css('z-index', '100')
$(".title_mike").css('width', '590px')
}, function() {
$("#james").css('z-index', '')
$(".title_mike").css('width', '')
});
});
$(function() {
$("#button1").hover(
function() {
$(".title_james").css('width', '785px')
}, function() {
$(".title_james").css('width', '')
});
});
</script>
what I am trying to get it to do is change the css styles two elements on hover over two large areas of text..
I have tried the mouseenter .addClass and mouseleave .removeClass thing and that didn't work at all.. so when I got this to work in firefox I was all happy... then I did cross browser checking and I got sad again..
You can see it live in action at:
http://roboticmonsters.com/who
Using the dev tools in Chrome it says there is an invalid token at the end of each of the javascript functions. The IE dev tools shows an invalid token too, but it seems to ignore this and render correctly. Check your source and remove the token, if you can.
IE:
Chrome:
$.css takes an object:
$("#james").css({'z-index': '100'});
Note the curly braces and colon (not comma).
This is so you can specify several css rules in one:
$("#james").css({'z-index': '100', 'height': '100px'});
If you are getting the value of a css rule, just pass in the name as a string:
$("#james").css('z-index'); // returns 100
It's possibly because you are trying to bind to those events before the DOM has loaded.
I didn't have much time to give you an answer as to why it was broken, but the following works for me in chrome.
$(document).ready(function() {
$("#button2").hover(function() {
$("#james").css('z-index', '100');
$(".title_mike").css('width', '590px');
},
function() {
$("#james").css('z-index', '');
$(".title_mike").css('width', '');
}
);
$("#button1").hover(function() {
$(".title_james").css('width', '785px');
},
function() {
$(".title_james").css('width', '');
}
);
});
if just use the code below it works fine:
$("#button2").hover(
function() {
$("#james").css('z-index', '100')
$(".title_mike").css('width', '590px')
}, function() {
$("#james").css('z-index', '')
$(".title_mike").css('width', '')
});
Otherwise Chrome reports: Unexpected token ILLEGAL. To see this yourself, right-click on the page and choose inspect element. Click the small red x in the bottom right.
Update: actually your code works fine if you remove the illegal character as shown in #anothershubery's answer