I'm not too sure why my code is causing this.
I have this jquery script in the header:
<script>
$(document).ready(function() {
$('.control').on('click', function(e) {
e.preventDefault();
var field = $(this).data('field');
$('.hider:visible').fadeOut("slow", function() {
$('#' + field + '-gallery, #' + field + '-tag').fadeIn("slow");
});
});
var randomIndex = Math.floor((Math.random() * 100) + 1) % 3;
console.log(randomIndex);
var field = $($('a').get(randomIndex)).data('field');
$('#' + field + '-gallery, #' + field + '-tag').fadeIn("slow");
});
</script>
when I reload the page, nothing happens so it appears the script isn't running. When I inspect the page on Chrome, I see there is this error which is in a tab called (program) and it's in the first few lines line:
if (window.top.require) {
Uncaught SyntaxError: Unexpected token ILLEGAL
window.top.require("ripple/bootstrap").inject(window, document);}
I don't know what it is in my code to cause this error. When I take out my script, it goes away. Not too sure if it's something with wordpress or jqueryUI (I have that loaded for another plugin).
You have an illegal invisible character on the last line between the ) and the ;.
Place your cursor after the ;, and start backspacing until you delete the ), then retype them both.
});
// ^^---between these
You'll notice that while backspacing, the cursor will fail to move one time. That's when the invisible character is being deleted.
This happens when copy/pasting code from jsFiddle or perhaps other similar sites.
The character is the unicode \u200B.
AFAIK, the script code you don't know where it comes from, is generated by the Blackberry emulator Ripple, when it inserts a generated script your document.documentElement (see at GitHub). I have seen this behavior causing problems in many of my projects, for example, being inserted on ajax results with dataType HTML and confusing my selectors, or getting my ajax responses dirtier in combination with jquery form plugin (can't link to it because of not enough reputation), etc. I think it might be interferring with your javascript? Hope it helps.
Related
I ran into a problem using jquery in IE for a background-url. I have some html (that contains a style with a background-url) that I make a jquery object from. After that I change some properties in this object and want back the outerhtml. This all works fine in chrome, but in IE it changes the background url a bit (removing slashes and adding quotes) because of this the url is not working anymore. I can add more slashes for IE, but I was wondering why this happens and if there is a better solution?
So the following peace of code will give the same html back in chrome as was put in, but in IE it has been altered:
function test() {
var logo = '<div class=\"item__img\" style=\"background-image: url(graphic?path=avatars\\OSDAFIJ-Employee_Large.JPEG?ts=1433171332313)\"></div>';
var $logo = $(logo);
var logoOuterHtml = $logo.prop('outerHTML');
console.info(logo + " || " + logoOuterHtml);
alert(logo === logoOuterHtml);
}
test();
Fiddle: https://jsfiddle.net/v7fs4xvr/
I am dynamically creating javascript and attaching it to the onclick event of links on my page using $(document).ready()
My onclick javascript is used to generate event functions that I am passing to Google Analytics to track events on my page, such as clicks on banners and downloaded PDFs. I am getting stats in Google Analytics for these events from every browser except for IE. So, something is wrong with my code in IE (I have searched and searched for errors on my page, there are none).
Normally I would just do something like $("a").click ... do stuff ... but for whatever reason, the only way I could get the Google Analytics event tracking to work was by putting the tracking event function directly on my links. So I'm using the following code to inject the tracking event function into my link's onclick once the page loads....
// Tracks favorites on the home page.
$("._gatHomePageFavorites").each
(
function(index)
{
var description = "Content ID: " + getParameterNamedID($(this).attr("href")) + " - " + $(this).children().first().attr("alt");
$(this).attr("onclick","alert('1');_gaq.push(['_trackEvent', 'Favorites - Home Page', 'Icon Click','" + _gatCleanString(description) + "']);alert('2');");
}
);
I think my problem is that IE is not putting my code on the onclick. But I don't know of a good way to view the generated source in IE. I have tried a couple of javascript functions in the address bar to bring up the generated source, assuming they work, then my code is not injecting the tracking event function into my link's onclick for IE. I see the tracking event function in the onclick in Firefox's view generated source.
As another test, you can see I added alerts around my tracking event funciton. In FF both alerts trigger, In IE neither alert triggers.
One more piece of info. My Google Analytics is not recording events for any IE browser. As far as I can tell, my issue is not specific to one version of IE.
How can I tell if my dynamic javascript is getting into the onclick for IE, and then what can I do to get it into the onclick for IE?
UPDATE
To simplify the problem and to focus the direction of the answers, I removed the Google Analytics event function. Now, all I am doing is injecting alert() into the onlick. IE won't even trigger the alert(). I have tried the following...
// Tracks favorites on the home page.
$("._gatHomePageFavorites").each
(
function(index)
{
$(this).attr("onclick","alert('1')");
}
);
and
// Tracks favorites on the home page.
$("._gatHomePageFavorites").each
(
function(index)
{
$(this).attr("onclick","setTimeout(\"alert('1')\", 1000);return false");
}
);
So I'm still leaning towards my javascript is not being injected into the onclick in IE.
What is the most reliable way to view generated source in IE?
If I can confirm that my code is not being injected into the onclick attribute of the link, then I can at least have an answer as to why Google Analytics isn't tracking events for IE. It would be because my injected code does not exist in IE.
You should not be adding the 'onclick' attr, but rather using this using jQuery .click() event.
function(index){
var description = "Content ID: " + getParameterNamedID($(this).attr("href")) + " - " + $(this).children().first().attr("alt");
$(this).click(function() {
alert('1');
_gaq.push(['_trackEvent', 'Favorites - Home Page', 'Icon Click', _gatCleanString(description)]);
alert('2');
});
}
something like above, sorry wrote this quick, so might have a typo.
Slim chance, but if you have any VBScript on your page then you should prepend your onclick string with "javascript:"
You could just use the time-honoured DOM0 onclick property, though there's really no decent reason why jQuery's click() method wouldn't work.
$("._gatHomePageFavorites").each
(
function(index)
{
var $this = $(this);
var description = "Content ID: "
+ getParameterNamedID($this.attr("href")) + " - "
+ $this.children().first().attr("alt");
this.onclick = function() {
alert('1');
_gaq.push(['_trackEvent', 'Favorites - Home Page', 'Icon Click',
_gatCleanString(description)]);
alert('2');
};
}
);
jQuery's attr() method is generally not useful, but that's a whole different rant.
Something to be aware of tracking links is that if the browser leaves the page before the tracking pixel is fetched, the event may not be recorded, depending on the browser, computer, & network speed. I've had good luck with the following (modified from #Tim Down's code):
$("._gatHomePageFavorites").each
(
function(index)
{
var $this = $(this);
var description = "Content ID: "
+ getParameterNamedID($this.attr("href")) + " - "
+ $this.children().first().attr("alt");
$this.click(function(e) {
alert('1');
_gaq.push(['_trackEvent', 'Favorites - Home Page', 'Icon Click',
_gatCleanString(description)]);
if ($this.attr('target') != '_blank') {
e.preventDefault();
setTimeout('document.location = "' + $this.attr('href') + '"', 150);
}
});
}
);
Essentially, if the link isn't opening in a new window, wait and follow it ourselves.
It turns out that my problem had nothing to do with Google Analytics or it's tracking event. After a lot of testing, I finally determined that in IE, jQuery's $().attr() was not working.
The odd thing was that it didn't break or throw an error. IE just ignored it somehow and would not add my dynamic javascript to the onclick parameter of the anchor tag.
Solutions...
The obvious one is to bind to the event like everyone suggested. If you can use $().click() then I agree, use it, always. Never use $().attr("onclick","do something");
However other circumstances in my project prevented me from using $().click(). I was unable to get stats into Google Analytics using it's event tracking function unless the event tracking function was inline on the anchor tag.
Went old school...
$(".obj").each
(
function (index) {
this.setAttribute("onclick", "alert('It is Working');");
}
);
Thanks for everyone's help.
I am working on a web page which contains a list of items and sub items for display. In the Div element, I am setting up the values, image. Using the image show and hide option On click event handler is triggered. This seems to be working fine with IE9, but doesn't work with other browsers (FireFox, Chrome and safari).
<div id="Type_A Medicine" value="H" entity="Type A Medicine" onClick="showHide(this,'MIE_Type_A Medicine')"><img src='<%=request.getContextPath()%>/images/plus.gif'>Type A Medicine</div>
function showHide(ctrl,id)
{
if (ctrl.value == "H")
{
ctrl.value = "S";
ctrl.innerHTML = "<img src='<%=request.getContextPath()%>/images/minus.gif'>" +ctrl.getAttribute("entity");
showBlock(id);
}
else if (ctrl.value == "S")
{
ctrl.value = "H";
ctrl.innerHTML = "<img src='<%=request.getContextPath()%>/images/plus.gif'>" + ctrl.getAttribute("entity");
hideBlock(id);
}
}
function hideBlock(blockId)
{
var str = "document.all." + blockId + ".style.display='none'";
eval(str);
}
function showBlock(blockId)
{
var str = "document.all." + blockId + ".style.display=''";
eval(str);
}
I still couldn't figure out the difference with the list of browsers. Kindly help...
I'm guessing it is because you use an invalid ID syntax. ID's cannot have spaces. If you use invalid HTML you can't expect javascript to work the same way across browsers.
id="Type_A Medicine"
Also, you never post the code for showBlock or hideBlock where you pass the ID in. Can't tell what goes wrong there without code.
To retrieve non-standard attributes, you should use .getAttribute() rather than trying to access them as properties.
So ctrl.entity should be ctrl.getAttribute("entity") and the same for other non-standard attributes. Run this example in Chrome: http://jsfiddle.net/jfriend00/Lxna7/.
Also, you should remove the space from your ID value as that's not a legal character and makes the id unusable in many circumstances (where a space is a delimiter between identifiers).
Try closing correctly the image tags to see if that fix the problem:
<img src="path/file.html" />
I want the file explorer to pop up for user selecting files when user click a button which is a <input id="J_upload_btn" type="button" />.
However the source above only works well on Firefox 4. On Chrome 11/12 and Firefox 3, the selecting-file-box pops up only after you click the button several times.
My jQuery version is 1.5.2.
$('#J_upload_btn').click(function() {
var _id = new Date().getTime(),
_$form = $('#J_pic_form'),
_$input = $('<input id="' + _id + '"' +
' type="file" name="file" class="hide_input">');
_$form.append(_$input);
_$input.trigger('click');
}
});
Unmatched closing curly brace. Just removing it should work.
You cannot reliably access DOM elements before the DOM tree is created. If this code is not wrapped in a function and called after that is the case, simply wrapping it in $(function(){ /* code */ }); is enough for jQuery to call it as soon as the DOM is ready.
In some browsers (including Firefox 3), triggering click events on <input type="file"> elements is restricted for security reasons.
This code works for me in Chrome:
$(function() {
$('#J_upload_btn').click(function() {
var _id = new Date().getTime(),
_$form = $('#J_pic_form'),
_$input = $('<input id="' + _id + '"' +
' type="file" name="file" class="hide_input">');
_$form.append(_$input);
_$input.trigger('click');
});
});
This kind of input is more restricted than others, by security issues. Sure there's a more current method, but the most common method to do this is using an invisible input (with opacity 0, not display:none), and placing a fake button over it, so when you click on the fake button, you're also clicking on the invisible input.
You may want to try not wrapping the input as a jayesh object. If you pass the HTML string to append, then the browser should add a new input field too.
var input = "<input id='"+id+"' />";
_$form.append(input);
Also, have you tried debugging the click in a console to make sure that it is getting fired or the subsequent code has the issue?
If you are tiggering click on the input, a function is expected to run. But as far as I can see, you have not written any function for the click event of _$input.
I want to detect and replace tab characters in a bit of HTML like this:
<code>
something
{ something else
}
</code
Right now, I am using something like this:
$(this).html(replaceAll(trim($(this).html()), "\t", " "));
But IE, in all its cleverness, changes tab characters into spaces, and so doing the above is useless. Does anyone know how I can detect tab characters in the HTML source with javascript for IE?
So, jmaglasang gave me a good idea. He said IE respects whitespace in a pre tag. So, I thought why not insert a pre tag with javascript, read the html, then remove the pre tag afterward. It works but theres a catch - you have to use a setTimeout callback. Heres the code:
$("code").each(function()
{ $(this).wrap("<pre></pre>");
var element = $(this);
setTimeout(function() // read the html
{ var x = element.html().split("");
for(n in x)
{ alert(x[n].charCodeAt(0) + " '" + x[n] + "'");
}
}, 0);
});
The setTimeout is neccessary because for some reason, IE waits to re-render the html until after all the javascript finishes running. Incidentally, it also waits to execute any callbacks issued by setTimeout. I wish I knew how I could force IE to render the html immediately... If anyone knows I'd definitely appreciate it.