Using jQuery (or JavaScript) to find and replace HTML special characters - javascript

I've been banging my head against a wall here for hours.
Long story short, I have a webpage that spits out the following HTML:
™
That HTML, of course, does not display properly so I need to dynamically convert to the following to get a proper trademark symbol:
™
I'm trying to achieve this either through JavaScript or jQuery.
I found one solution that works locally on a test webpage I set up:
$('body').html($('body').html().replace('™','™'));
But the problem is when I add that to the actual website it needs to go on, it does not work and instead seems to have some kind of conflict the the other jQuery methods being used.
I'm at my wit's end. Any help would be greatly appreciated. Thanks!
EDIT: Sorry everyone... To be more specific, this is a WordPress website and the problem appears on a page that is generated via this sitemap plugin: http://wordpress.org/extend/plugins/sitemap-generator/.
The problem is not with that plugin necessarily, but in how that plugin interprets WordPress page titles with special characters.
There is a page that I created in WordPress which needs to have a title with the ™ symbol at the end, so in the WordPress page title area I added
™
to the end of the title text. This totally works in all aspects of the website, except that when this plugin reads the title it converts it to
™
I suppose I could try to edit the plugin and how it handles HTML special characters in WordPress page titles, but I knowledge of php is not incredibly strong so I thought an easier fix would be to manipulate the output using js since there is only 1 instance that needs to be fixed.
I am going to try the solution presented below and I will report back with the findings.
Thanks again!
ADDITIONAL EDIT:
Ok using the solution posted below I got it to work. However the placement of the new code is important. When I put it at the end of my JavaScript the dropdown menus in my navigation bar would not work. When I put the new code before my JS menu call, everything seemed to work fine.
Perhaps someone on here can shed some light as to why I need to put this new line of code before the call to the navigation method (superfish).
Here is the new JS that's included in the header. Note the new line near the top that starts with "document.body.innerHTML"
<script>
$(document).ready(function(){
document.body.innerHTML = document.body.innerHTML.replace(/&trade;/g, "™");
$("ul.sf-menu").supersubs({
minWidth: 12, // minimum width of sub-menus in em units
maxWidth: 27, // maximum width of sub-menus in em units
extraWidth: 1 // extra width can ensure lines don't sometimes turn over
// due to slight rounding differences and font-family
}).superfish(); // call supersubs first, then superfish, so that subs are
// not display:none when measuring. Call before initialising
// containing tabs for same reason.
// hide #back-top first
$("#back-top").hide();
// fade in #back-top
$(function () {
$(window).scroll(function () {
if ($(this).scrollTop() > 100) {
$('#back-top').fadeIn();
} else {
$('#back-top').fadeOut();
}
});
// scroll body to 0px on click
$('#back-top a').click(function () {
$('body,html').animate({
scrollTop: 0
}, 400);
return false;
});
});
$('.slideshow').cycle({
fx: 'fade', // choose your transition type, ex: fade, scrollUp, shuffle, etc...
cleartypeNoBg: false // This fix is needed to prevent black pixels from disapeparing during transitions in IE. Must use jquery.cycle.min for this attribute to be supported.
});
$(".section_page_list li:last").css({borderBottom: 'none'});
$(".striped_table td:even").addClass("make_divider");
$(".striped_table tr:even").addClass("alternate");
$(".homepage_article_table td:odd").addClass("alternate");
$(".homepage_article_table tr:last td").css({borderBottom: 'none'});
$(".striped_table tr:first-child").addClass("first");
$(".report_table tr:first-child").addClass("first");
$(".press_table tr:even").addClass("alternate");
$(".press_table tr:first-child").addClass("first");
$(".press_table tr td:first-child").addClass("no_border");
});
</script>

If its due to jQuery conflict the below should solve it. Its plain JavaScript code.
document.body.innerHTML = document.body.innerHTML.replace(/&trade;/g, "™");
Don't you have access to the server side code of the page? If you have it then you would be better changing that code to spit the required thing instead of using JS.

For Brackets like characters
If you want to replace characters like ( or ) etc. you can make use of \ before that character.
e.g. If I want to replace () with word 'Hidden'
return x.replace(/\(\)/g, 'Hidden');

What does your source say? If the source has '™' then you probably have a javascript error before ever hitting this line.
I'd suggest it's also possible that your live server is further encoding your output - so that '&trade;' becomes '&amp;trade;'

Related

Load page partially via javascript?

I guess there are already posts on this topic, but I couldn't find anything with search terms like: "load page partially javascript", "content loading javascript", etc.
My question is how would you load a page to not display 100% of the content, but load it, for example, when you scroll.
Example: https://chrome.google.com/webstore/category/extensions?hl=de
I don't need someone to code this now, I would highly appreciate if someone just had a tutorial or anything similar on this.
My approach for doing this was to use a combination of javascript and JQuery. Something like this:
window.onScroll = checkScroll(event);
function checkScroll(event)
{
position = $(window).scrollTop();
/* note the () are necessary to obtain a value that represents
the page vertical position, otherwise you will be just sending
the browser to the top, like a refresh */
if (position == 1000) /* some pre-determined vertical position */
{
$(#AnchorDiv).append(htmlString);
/* Where AnchorDiv is the id of the element where you want to
insert new code, and htmlString is a javascript string which contains
the new HTML block.*/
}
}
Note: you can also use Jquery's .position method to obtain the position of an element rather than hard-coding it like I did with the 1000 example.
I Hope this helps. I'll be curious to see how it works out - and/or how other folks respond to this question - and/or of you find another good working alternative.

jQuery .attr Not Working Properly, Miss-Retrieving Links

This is a page I'm currently working on as a project
$(function() {
$(".modal-launcher, #modal-background").click(function() {
$(".modal-content, #modal-background").toggleClass("active");
$(".vid-1i").attr("src", "link1");
$(".vid-2i").attr("src", "link2");
$(".vid-3i").attr("src", "link3");
$(".vid-4i").attr("src", "link4");
$(".vid-5i").attr("src", "link5");
$(".vid-6i").attr("src", "link6");
$(".vid-7i").attr("src", "link7");
$(".vid-8i").attr("src", "link8");
//$('html').toggleClass('active').css('top', -(document.documentElement.scrollTop) + 'px');//
});
});
above the actual links are replaced just to display a quick idea of the bad jQuery.
In it, I am attempting to create my own popup launcher for videos; however, I am having trouble using jQuery to replace the "" src of an iframe element to a YouTube link. I am unable to figure out why the jQuery is not working. I understand that the jQuery is, of course, working properly, and that it is me who has written the code incorrectly, but here I am asking if anyone is able to figure out what it is I've done wrong, or what can be changed to make it work.
For some reason, the last video in the jQuery list is always the one retrieved.
Understand that the images are missing from the page due to them being local files and not network locations. Clicking above the captions that read like "Match One" will have the "intended" result, regardless if the image is showing or not.
Coming back to this and understanding more of JavaScript and jQuery, my problem was simply misunderstanding the code. In order to do something like this, one function per link would be more suitable.
function video1()
{
$("#popup, #modal-background").toggleClass("active");
$("#popup").prop("src", "https://www.youtube.com/embed/7h1s15n74r3all1nk");
document.getElementById('scroll').style.cssText ='overflow:hidden';
}
complementary html would look like this:
<div onclick="video1()"></div>
The previous code would run each line, effectively setting the last link as the source of the element. The new code is button independent, ensuring only one link belongs to each button.

Combining jQuery libraries: realistic-typewriter.js and waypoint.js

I am currently designing a website for a university project based around the open source project. My website is based around an infinite scroll layout, the idea is for each section to have a terminal that looks like the command line and to have the text print to these screens.
I have implemented realistic-typewriter.js (https://github.com/fardjad/realistic-typewriter.js) for the self-typing text. To have the animations triggered at pre-defined moments (when the user is at that section of the page) I have been told to use waypoint.js (https://github.com/imakewebthings/jquery-waypoints)
Now my problem is implementing the 2 together.
Typewriter.js is implemented something like this.
var typewriter = require('typewriter');
var twSpan = document.getElementById('typewriter');
var tw = typewriter(targetDomElement).withAccuracy(90)
.withMinimumSpeed(5)
.withMaximumSpeed(10)
.build();
tw.clear()
.type('TEXT GOES IN HERE')
});
What I don't understand here is the syntax of the variables at the start, it seems a bit convulted to my amateur eye.
The tw.clear() line - I assume the tw is the variable and the .clear does what?
Now the waypoint library - I was previously using this fine with the typed.js library, but its functionality was a bit limited and I was advised to move over to realistic-typewriter.js, the code doesn't seem to work in the same way with realistic-typewriter.js.
Here is the example code for waypoint.js from its documentation.
$('.thing').waypoint(function() {
// i tried to put the above code in here but it doesn't seem to work
); offset: '50%'
});
Basically I need to know how to combine waypoint.js and realistic-typewriter.js, but any explanations of the working processes of these would also be really helpful.
tw is an object that is accessing the "clear" method, which I am guessing clears out the element so it can type in it.
Also, looks like your waypoints code something is off. Should be something like:
$('.thing').waypoint(function() {
//code goes here
}, { offset: '50%' });
If you place the realistic-typewriter code there it should run it once you've reached that element.

Replacing paragraph tag contents with a random word from javascript

When a user enters the page I would like a div to be in the center with a heading, a quote underneath that is randomly picked from a list and a button to enter the site. This is all well and good but I cannot seem to get the button to fade in the main site and fade out the landing div. Here is a jsfiddle to try and help explain things more.
JSFIDDLE
As you will probably be able to tell, I'm not that great with JavaScript or jquery and what I have done so far is from learning bits and pieces and surfing the web through code examples
I do not see why it will not work as I had a play around in jsfiddle with a simplified version of what I want to do and it worked.
Simplified Version
Below code is simplified version (It wouldn't let me post without adding code?)
HTML
<div class="landingDiv">
<h1>LANDING DIV</h1>
<button id="showMain">Enter Site</button>
</div>
<div class="main">
<h1>Main Site</h1>
</div>
JQUERY
$("#showMain").click(function () {
$(".main").fadeIn(1000);
$(".landingDiv").fadeOut(1000);
});
CSS
.main {
display: none;
opactiy: 0;
}
Thanks in advanced.
Steve.
The first jQuery example threw an error:
$ is not defined
meaning jQuery is not defined/included. Which it wasn't. But in the second jsFiddle, you included jQuery.
You'll notice that on the left hand side of jsfiddle, you'll see that under the "Framewords & Extensions" heading that you can include a Framewordk - so, include jQuery!
Here is the updated fiddle with jQuery included: http://jsfiddle.net/6cGHF/1/
As you move forward in your JavaScript development, it is always a good idea to check your browsers developer tools for errors when something unexpected is happening. It always helps you, and when you ask questions on StackOverflow, providing these errors help us! :)
The shortcut for developer tools in Chrome is F12 - you can see a little red circle with an X in it if you have errors - click it for more info. But developer tools are also available in other major browsers (except IE8 and below).
Edit:
Wrap your click() event function in a $(document).ready()
$(document).ready(function() {
$("#showMain").click(function () {
$(".main").fadeIn(1000);
$(".landingDiv").fadeOut(1000);
});
});
What was happening was that your HTML file is read from top to bottom. So it would have reached your click function before the #showMain element had been read. So, jQuery couldn't find it.
The reason this wasn't a problem in jsFiddle was because all the JavaScript code was wrapped in an "onLoad" function (which is, admittedly, a little different to $(document).ready()) but it solved this problem for you by executing your JavaScript after everything had already been loaded. You can see that on the left hand side in the fiddle I linked above, you'll find a dropdown with "onLoad" selected. In it, you can also choose "OnDomready" (which would be equivalent to $(document).ready())
In summary:
DON'T use $(document).ready() in jsFiddle. You don't need it.
DO use $(document).ready() around javascript that relies on the fact that the DOM is ready (ie. "all of your content is visible to your JavaScript").
The problem in your fiddle is you have not added jQuery so when you try and reference it with '$', a javascript error is thrown. Simply add in the reference to a jQuery library and your fiddle works to fade out the button when clicked.
Your problems:
1) Add jQuery library to your fiddle.
2) Remove opacity:0; from .main in your CSS. The display:none; is sufficient.
3) Use this to fade out/in the elements:
$("#showMain").click(function () {
$(".landingDiv").fadeOut(1000, function () {
$(".main").fadeIn(1000);
})
});

A mysterious situation with jQuery or am I blind?

i have a jQuery code and the html code on my page. The code loads two php files on two DIVs, based on the value of a drop down list. The code is working great, loading pic and everything. However I have a small problem.
When I place the second div ( artistdetails ) inside of a seperated div from the first div, the loading pic does not appears on the second but only in the first. Content is appeared correctly though.
As I saw in firebug, the class is loading fine. I even changed the picture to something bigger but nothing was there. ( I mean the pic is not hidden somewhere).
I made a lot of experiment, I set the ID to the float:left div but nothing happens. I really need to have them in a separated DIV. Is that possible?
I would start looking at the final generated code (which you might post here or on pastebin.com with a link).
Sounds to me like something in the php forms is probably not generating valid html. For example, an unclosed entity.
It must work, i guess, if the class is added to <div id="artistdetails"></div>
Still try something like this
$('#artistdetails').empty()
.addClass('loading')
.load('forms/' + val + 'b.php',
function(){
setTimeout(
function(){ $('#artistdetails').removeClass('loading') },
2000);
});

Categories

Resources