Code isn't compatible with IE? - javascript

$(document).ready(function() {
var url = document.location.toString();
$('.tab').click(function() {
if($(this).is(".active")) {
return;
}
var classy = $(this).attr("class").split(" ").splice(-1);
var innerhtml = $('.content.'+classy).text();
$('#holder').html(innerhtml);
$('.tab').removeClass('active');
$(this).addClass('active');
});
var url = document.location.toString();
if(url.match(/#([a-z])/)) {
//There is a hash, followed by letters in it, therefore the user is targetting a page.
var split = url.split("#").splice(-1);
$('.tab.'+split).click();
}
else {
$('.tab:first').click();
}
});
Hey, I was just informed by one of my commenters that this code doesn't work in IE. I can't for the life of me figure out why. Whenever you switch tabs, the content of the tab doesn't change. Meanwhile the content of the #holder div is all the tabs combined.
Any ideas?

Not the answer you're after, but I'd seriously recommend looking into the jQueryui tabs widget if you can. It's made my life a lot easier dealing with this stuff at least.

Hard to tell without an IE version and a page to look at what exactly is happening- but here are some best guesses:
change:
if($(this).is(".active")) {
to:
if($(this).hasClass("active")) {
change:
var innerhtml = $('.content.'+classy).text();
to:
var innerhtml = $('.content .'+classy).text(); // note the space
change:
var url = document.location.toString();
to:
var url = document.location.hash;

I did all changes which Ryan suggested except adding the space between '.content' and the period as it is needed. He could not have known without the source code.
I changed your .splice(-1) to [1] so that I'm choosing the second item in the array, which is the class name. It looks like .splice(-1) is behaving differently in IE and other browsers.
I have tested the code with IE 7-8 and it works.
Source code as it is now:
$(document).ready(function() {
var url = document.location.hash;
$('.tab').click(function() {
if ($(this).hasClass("active")) {
return;
}
var classy = $(this).attr("class").split(" ")[1];
var innerhtml = $('.content.' + classy).text();
$('#holder').html(innerhtml).slideDown("slow");
$('.tab').removeClass('active');
$(this).addClass('active');
});
if (url.match(/#([a-z])/)) {
//There is a hash, followed by letters in it, therefore the user is targetting a page.
var split = url.split("#")[1];
$('.tab.' + split).click();
}
else {
$('.tab:first').click();
}
});

Related

Adding a target="_blank" with execCommand 'createlink'

I am attempting to create a mini WYSIWYG editor for a custom CMS. It has the option to add and remove links. It adds links fine, but would like to have the option to add target="_blank" to the hyperlink. Also, if possible, I would like to be able to add alt="" and title="".
At the moment this is my code:
function addLink() {
var linkURL = prompt('Enter a URL:', 'http://');
editorWindow.document.execCommand('createlink', false, linkURL);
}
Been looking around, and can't seem to find a solution. Most of the solutions I've seen say to add:
function addLink() {
var linkURL = prompt('Enter a URL:', 'http://');
var newLink = editorWindow.document.execCommand('createlink', false, linkURL);
newLink.target = "_blank";
}
But this doesn't seem to work. Any suggestions?
I was able to find a solution. Don't know if this is the right way to go, but it works. Following https://stackoverflow.com/a/5605841/997632, this is what I used for my code to work:
function addLink() {
var linkURL = prompt('Enter a URL:', 'http://');
var sText = editorWindow.document.getSelection();
editorWindow.document.execCommand('insertHTML', false, '' + sText + '');
}
Just in case anyone else is looking and stumbles upon this...
insertHTML can be frustrated if you have a bold or italic before.
I use the following approach:
var url = 'example.com';
var selection = document.getSelection();
document.execCommand('createLink', true, url);
selection.anchorNode.parentElement.target = '_blank';
I know this thread is quite old, but let me throw my 2 cents in, and maybe someone will find this useful ;)
I'm working on a WYSIWYG editor too As I found the accepted solution fails for me when I try to make a link from a selected image in FF (the getSelection().getRangeAt(0) returns the image's parent div and treats the image as it never wasn't there (this is how I see it)), here's a dirty but working (and, I think, it's turbo-cross-browser) idea I came up with (jQuery):
//somewhere before losing the focus:
sel = window.getSelection().getRangeAt(0);
//reselecting:
window.getSelection().addRange(sel);
//link:
document.execCommand('createLink', false, 'LINK_TO_CHANGE');
$('a[href="LINK_TO_CHANGE"').attr('target', '_blank');
//any other attr changes here
$('a[href="LINK_TO_CHANGE"').attr('href', theRealHref);
Is it good idea? Works like a charm. And this simplicity ^^
Since, there is no straightforward cross-browser solution, one cross-browser workaround could be programatically attaching an event handler to a inside your editor:
var aLinks = Array.prototype.slice.call(editorElement.querySelectorAll('a'));
aLinks.forEach(function(link) {
link.addEventListener('click', function() {
window.open(link.href, '_blank');
});
});
Nobody seems to mention that as per specs, the document has to be in the design mode:
document.designMode = "on";
Then the following should work:
var url = 'http://google.com';
var selection = document.getSelection();
document.execCommand('createLink', true, url);
The execCommand'createLink' does not always work. It will sometimes wrap the link text inside a link.
i.e
<a>label</a>
Resulting the html link code appearing in the document and the link not working.
in this case ues execCommand 'insertHTML'
val=``+label+``
//document.execCommand('createLink', false, val);
document.execCommand('insertHTML', false, val);

This script applies specific attr to all links on the website. How to exclude pdf and zip files?

I'm building Wordpress website where all pages are being loaded using Ajax. I'm using script created by Chris Coyer that can be found here. Code below will add specific tags to all links on the website. Wordpress will try to load content from those links using Ajax. Problem is that those attributes are being applied on links to PDF and ZIP files which are meant to be downloaded, not loaded into page.
How I can exclude specific file formats from getting those attributes? I already tried something like this $internalLinks = $("a[href^='"+siteURL+"']:not([href$=/*.pdf])") but that didn't work for me. Am I doing something wrong?
Below is part of the original code that adds attributes. Full code can be found on this JSFiddle page. Thanks!
var $mainContent = $("#main-content"),
siteURL = "http://" + top.location.host.toString(),
$el = $("a");
function hashizeLinks() {
$("a[href^='" + siteURL + "']").each(function() {
$el = $(this);
// Hack for IE, which seemed to apply the hash tag to the link weird
if ($.browser.msie) {
$el.attr("href", "#/" + this.pathname).attr("rel", "internal");
} else {
$el.attr("href", "#" + this.pathname).attr("rel", "internal");
}
});
};​
You can't use * as a wildcard like a filespec. Just use this:
$internalLinks = $("a[href^='"+siteURL+"'):not([href$='.pdf'])");
You can apply a filter on all matched links:
var $mainContent = $("#main-content"),
siteURL = "http://" + top.location.host.toString(),
$el = $("a");
function hashizeLinks() {
$("a[href^='" + siteURL + "']").filter(function(){
return this.href.match(/[^\.pdf]$/i);
}).each(function() {
$el = $(this);
// Hack for IE, which seemed to apply the hash tag to the link weird
if ($.browser.msie) {
$el.attr("href", "#/" + this.pathname).attr("rel", "internal");
} else {
$el.attr("href", "#" + this.pathname).attr("rel", "internal");
}
});
};​

&-sign is ruining my link-rewriter

I'm currently writing a userscript that runs on another site. One function is to rewrite the links so you skip one landing page. However, if the &-sign exists in the link, my function will output it as & instead of &.
$('a').each(function(index) {
var aLink = $(this).attr('href');
if(aLink) {
if(aLink.indexOf("leave.php?u=") > 0) {
aLink = aLink.substring(38);
$(this).attr('href', decodeURIComponent(aLink));
}
}
});
This is one example of a link that gets ruined:
https://www.site.com/exit.php?u=http%3A%2F%2Fsverigesradio.se%2Fsida%2Fartikel.aspx%3Fprogramid%3D104%26amp%3Bartikel%3D3406950
Is a link to:
http://sverigesradio.se/sida/artikel.aspx?programid=104&artikel=3406950
But becomes this instead:
http://sverigesradio.se/sida/artikel.aspx?programid=104&artikel=3406950
The & entity is built right into that URL, so there's nothing for it except to just replace it.
Use:
aLink = aLink.substring (38);
aLink = decodeURIComponent (aLink);
aLink = aLink.replace (/&/gi, "&");
$(this).attr ('href', aLink);

Class of ID Change based on URL - URL Based Image Swap -

What I'm trying to achieve:
Based on URL (ie., foo.com/item1), the div element "logoswap" receives a different class.
The following is the code I put together but it seems completely wrong. I'm not a JS pro by any means, XHTML/CSS is more my speed (some PHP)... I cannot use PHP, even if it is possible in PHP (and I know it is because I have a PHP version of what I need done already, but I can't call the PHP properly.
I'm really just trying to get a different logo to show up based on the directory/url... It doesn't have to be a background element called in by the CSS class necessarily, I just need a different image to load based on the aforementioned url variable...
$(function() {
var url = location.pathname;
if(url.indexOf('item1') > -1) {
document.getElementById("logoswap").className += " class1";
}
elseif(url.indexOf('item2') > -1) {
document.getElementById("logoswap").className += "class2";
}
elseif(url.indexOf('item3') > -1) {
document.getElementById("logoswap").className += "class3";
}
elseif(url.indexOf('item4') > -1) {
document.getElementById("logoswap").className += "class4";
}
elseif(url.indexOf('item5') > -1) {
document.getElementById("logoswap").className += "class5";
}
else {
document.getElementById("logoswap").className += "class1";
}
});
That's what I have... Ugly I'm sure.
That's why I'm here though, I definitely need some help.
Assigning CSS Class By URL Pathname
A jsfiddle has been setup for
this solution.
Here is a case for using numeric expressions if they are available. This does not apply to the above question.
$(function() {
var rgx = /item(\d+)$/,
url = location.pathname,
id = (rgx.test(url)) ? url.match(rgx)[1] : '1';
$("#logoswap").addClass("class" + id);
});
UPDATE:
In light of the new details you may need an array of values, these should be derived from or exactly equal to the class names you intend to use.
$(function(){
// my favorite way to make string arrays.
var matches = "brand1 brand2 brand3".split(" "),
url = location.pathname.match(/\w+$/)[0], // get the last item
id = matches.indexOf(url),
className = matches[(id > -1) ? id : 0];
$("#logoswap").addClass(className);
});
To make this work you will need a few things in place. I will assume that the paths will end in a number as we have outlined here. The default ends with 1. You will need the images to be accessible. You need to define the styles for each possibility.
CSS Setup
#logoswap {
height : 200px;
width : 200px;
}
.class1 {
background-image : url(/path/to/default.jpg);
}
.class2 {
background-image : url(/path/to/second.jpg);
}
.brand1 {
background-image : url(/path/to/brand/1/logo.jpg);
}
...
Without jQuery
if you do not have jQuery in your code you may need to use window.onload.
(function(){
var old = window.onload;
window.onload = function(){
old();
var r = /item(\d+)$/,
url = location.pathname,
id = (r.test(url)) ? url.match(r)[1] : '1';
document.getElementById('logoswap').className += "class" + id;
};
})()
I just want to take a moment here to
encourage anyone who is doing this
type of code to get used to Regular
Expressions and learn them. They are
far and away the most frequently used
cross language part of my development
arsenal.
There's nothing that wrong with what you have. You could tidy it up with something like below.
$(function() {
var url = location.pathname;
var logo = document.getElementById("logoswap");
var i = 6;
logo.className = "class1";
while(i--)
{
if(url.indexOf("item" + i) > -1) {
logo.className = "class" + i;
}
}
});
Hope this helps.
Using just HTML/CSS, you could add (or append via javascript) an id to the body of the page:
<body id="item1">
Then in your CSS, create a selector:
#item1 #logoswap {
// class1 CSS
}

Highlight a button based on location

I'm trying to highlight a navigational button (in a menu) based on the page being viewed. Here is what I have so far:
var loca = String(document.location.href);
// Get document location and specific page.
if (loca) {
if(loca.search(RegExp("((/[\w]*)\.php)")) != -1) {
activate(loca.match(RegExp("((/[\w]*)\.php)").split("/").join("")));
} else {
activate("home");
}
}
// Activate a button
function activate(bName) {
$(".button[name=" + bName + "]").css({
"border-left": "1px solid white",
"border-right": "1px solid white"
});
}
What I want to happen is this:
Get URL of page
Get the specific file name of page, and if not found, then we are on the homepage.
Using jQuery, I try to find the name of the button, and if the name matches the filename, then highlight it.
Thing is, this only highlights the "Home" button. What am I doing wrong? Also, if you have any suggestions on how I can better accomplish this, please let me know!
I would get the filename like this, instead:
var pathname = window.location.pathname.split("/");
var filename = pathname[pathname.length-1].split(".")[0];
alert(filename);
Your regular expression is incorrect.
var loc_match = window.location.href.match(/(\w+)\.php/);
activate(loc_match ? loc_match[1] : "home");
I don't have a solution but I would assume the regex is flawed. Did you try to store the result in a variable and console.log it?
I've actually implemented something like this. Here's my code:
var currentPage = window.location.pathname.toLowerCase().split('/').reverse()[0].split('#')[0].split('?')[0];
if (!currentPage || currentPage == '')
{
currentPage = 'default.aspx';
}
$('#nav li').removeClass('current').each(function() {
var href = $(this).find('a').first().attr('href');
if (href && href.toLowerCase().indexOf(currentPage) >= 0)
{
$(this).addClass('current');
}
});
This takes into account any query strings or searches may be in the URL. Using reverse() may not be the most efficient way of doing it, but it certainly works.
When you declare your regexp as new RegExp object, you have to use double backslash escaping symbols (instead one backslash, when you just assign literal like var a = /\w/i; );
So, your code should work after some reg exp correction:
var loca = document.location.href;
var pattern = new RegExp("[\\w]*(?=\\.php)","i");
// Get document location and specific page.
if(pattern.test(loca)) {
activate(pattern.exec(loca));
} else {
activate("home");
}
// Activate a button
function activate(bName) {
$(".button[name=" + bName + "]").addClass('active')
}
And as already said, it's easier to assign class to your active element.

Categories

Resources