jQuery .hover not working in Safari or Chrome - javascript

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

Related

jquery .each function conflicts when changing DOM

Does anyone have a clue why this function only works partially in both scenarios (with tampermonkey extension)
Html:
<div class="container">
<p>
<a onclick="alert('item clicked')" class="">Element to auto click</a>
Element to open in new tab
</p>
</div>
Version 1:
setTimeout(function(){
$('.container a[href*="telechargement"]').each(function() {
$(this).attr("target", "_blank"); //not working
console.log(this) // see image bellow
$(this).prev()[0].click(); //working
});
}, 1000);
Version 2 (almost identical):
setTimeout(function(){
$('.container a[href*="telechargement"]').each(function() {
$(this).attr("target", "_blank"); //working
console.log(this) // see image bellow (same result)
$(this).prev().click(); //not working
});
}, 1000);
The console returns target="_blank" in both scenarios, but on the first scenario the DOM has not changed, so there is no target attribute. Why does it behave like this?
It seems to work in fiddle so I might be looking in the wrong place https://jsfiddle.net/n71w52hy/2/
. Could this come from TamperMonkey? Any suggestion welcome.
Thanks hips.

jquery ON event not firing in IE8

I made this jsfiddle to demonstrate what I am meaning, but unfortunately JSfiddle itself doesn't seem to work with IE8 so you need to test this jsfiddle code in a stand alone page:
http://jsfiddle.net/4Bdbn/
With IE8 the above ON events does not fire, absolutely nothing happens. even adding an alert("hi") to the function does nothing; it doesn't get called, plus no errors are reporting in the console.
On a side note, is e.preventDefault() necessary to prevent a function being executed multiple times when you have multiple events triggering the same function, such as .on("touchstart click",....? In all situations?
jQuery version 1.8.3 so I believe IE8 is a supported browser.
ps. Im using IE10 in Browser Mode IE8.
EDIT: My simple test page which is not working in IE8 (for me):
http://www.personaltrainer.com.au/test.php
The relevant code section is...
<script type="application/javascript">
$(document).ready(function () {
$("body").on("click touchstart",".something",function(e) {
$(this).text($(this).text() + " "+e.type);
e.preventDefault();
});
});
</script>
Thanks!
You're using an invalid type attribute (application/javascript) on your script tag. Change it to text/javascript or simply remove it all together.
This works just fine in IE8 (real version)
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("body").on("click touchstart",".something",function(e) {
$(this).text($(this).text() + " "+e.type);
});
});
</script>
maybe you should remove the touchstart event first to check if it works! IE8 actually dosn't support touch action!
$(function () {
$("body").on("click",".something", function(e) {
$(this).text($(this).text() + " " + e.type);
//e.preventDefault();
});
});

Console.log not working at all

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.

JQuery & Browser Compatibility regarding :focus

Ok it seems ive stumbled on another JQuery problem but i think this is more off a browser problem. The code below seems to work fine in All browsers apart from IE7 & Opera
function inputs() {
$('#search').css({opacity: .25}).hoverIntent( function() {
$(this).stop(true,true).animate({opacity: 1}, 500 );
},
function() {
if(!$('#mod_search_searchword').is(':focus') ) {
$('#search').stop().delay(500).animate({opacity: .25}, 500 );
}
}
);
$('#search').focusout(function(){$(this).stop(true,true).animate({opacity: .25}, 500 );});
}
The effect is simple... I just want it so that once the search input field is hovered to raise its opacity then when its hovered out to revert back to original opacity, but if the input field is active to not execute the hoverout till they focus out. But for some reason :focus doesnt seem to be recognised by opera or IE7. Is there a work around?
I did not find the :focus selector in the latest jQuery docs.
You have to extend jQuery to use this feature.Answered here
Try this out.
setTimeout(function() { document.getElementById('mod_search_searchword').focus(); }, 10);
or you can also use :active

How to replace href using javascript regex in Firefox?

I try to change some links on a webpage using the following code for jQuery on Rails
$(function () {
$('#lesson a').live('click', function () {
$.getScript(this.href.replace(/^(http...[^\/]+)?\/+(.*)$/,'/ajax/\\$2'));
return false;
});
})
This trick works for Chrome and Safari, but fails (nothing happens on click) for Firefox and Opera. What can be wrong with the code?
EDIT1:
The webpage contains:
<div id="lesson">
Subject 1
...
</div>
On click, a browser (i.e. Firefox and Opera) should make an ajax-request of /ajax/subj1.
You replace the string with '/ajax/\\$2'.
You have an extra backslash - if you expect the result /ajax/subj1, use '/ajax/$2'.

Categories

Resources