Use Javascript to modify mso comment in HTML code? - javascript

I am currently trying to develop a small tool that changes certain elements in an html file - one of those elements is a "bulletproof CSS button" for email as seen in the following page:
Campaign Monitor
The commented block of code looks like this:
<!--[if mso]><v:roundrect xmlns:v="urn:schemas-microsoft-com:vml" xmlns:w="urn:schemas-microsoft-com:office:word" href="http://google.com" style="height:30px;v-text-anchor:middle;width:170px;" arcsize="9%" stroke="f" fillcolor="#34adb2"><w:anchorlock><center></center></w:anchorlock></v:roundrect><![endif]-->
Now, as you can see, such code contains an mso comment, I was wondering if there is any way to use Javascript to target this element and change the href attribute, I have tried alerting the commented elements on the page using the following code:
$(function() {
$("body").contents().filter(function(){
return this.nodeType == 8;
}).each(function(i, e){
alert(e.nodeValue);
});
});
So far this only alerts the native HTML comments and not the specific mso comment I'd like to change.
Is there any other way to target this comment? Any help will be greatly appreciated!

I wrote some simple codes in various scenarios, you can use one of them base witch you want. ;)
I tested them by IE 11
In these examples we have some HREFs value:
www.mysite. com << this is the default value
www.example.com << this is our new value
Now codes:
HTML
This:
<div id="mybtn">
Show me the button!
<!--[if mso]><v:roundrect xmlns:v="urn:schemas-microsoft-com:vml" xmlns:w="urn:schemas-microsoft-com:office:word" href="http://http://www.mySite. com" style="height:40px;v-text-anchor:middle;width:200px;" arcsize="10%" strokecolor="#1e3650" fill="t">
<v:fill type="tile" src="http://i.imgur.com/0xPEf.gif" color="#556270" />
<w:anchorlock/>
<center style="color:#ffffff;font-family:sans-serif;font-size:13px;font-weight:bold;">Show me the button!</center>
</v:roundrect><![endif]-->
</div>
Or this:
<div id="mybtn">
<!--[if mso]><v:roundrect xmlns:v="urn:schemas-microsoft-com:vml" xmlns:w="urn:schemas-microsoft-com:office:word" href="http://http://www.mySite. com" style="height:40px;v-text-anchor:middle;width:200px;" arcsize="10%" strokecolor="#1e3650" fill="t">
<v:fill type="tile" src="http://i.imgur.com/0xPEf.gif" color="#556270" />
<w:anchorlock/>
<center style="color:#ffffff;font-family:sans-serif;font-size:13px;font-weight:bold;">Show me the button!</center>
</v:roundrect><![endif]-->
Show me the button!
</div>
The codes state before running any scripts:
.
.
A) Javascript (just Changing HREF property of v:roundrect tag)
$("div#mybtn").contents().filter(
function(){
return this.nodeType == 8;
}).each(function(i,e){
if(i==0)
{
$(this)[0].data = replaceHrefWithNew($(this)[0].data,"http://www.example.com");
console.log($(this));
}
});
function replaceHrefWithNew(myMso,newHrefValue)
{
var newMso=myMso;
var indexOfStartHref=myMso.indexOf("href")+6;
if(indexOfStartHref>=6)
{
var indexOfEndHref=myMso.indexOf("\"",indexOfStartHref);
var part1=myMso.substring(0,indexOfStartHref);
var part2=myMso.substring(indexOfStartHref,indexOfEndHref);
var part3=myMso.substring(indexOfEndHref);
newMso= part1 + newHrefValue + part3;
}
alert(newMso);
return newMso;
}
Result after run Script A
.
.
B) Javascript (Changing HREF property of v:roundrect tag & A tag together)
$(document).ready(function(){
var webAddress="http://www.example.com";
$("div#mybtn").contents().filter(
function(){
return this.nodeType == 8;
}).each(function(i,e){
if(i==0)
{
$(this)[0].data = replaceHrefWithNew($(this)[0].data,webAddress);
console.log($(this));
}
});
$("div#mybtn").find('a:first').prop("href",webAddress);
});
function replaceHrefWithNew(myMso,newHrefValue)
{
var newMso=myMso;
var indexOfStartHref=myMso.indexOf("href")+6;
if(indexOfStartHref>=6)
{
var indexOfEndHref=myMso.indexOf("\"",indexOfStartHref);
var part1=myMso.substring(0,indexOfStartHref);
var part2=myMso.substring(indexOfStartHref,indexOfEndHref);
var part3=myMso.substring(indexOfEndHref);
newMso= part1 + newHrefValue + part3;
}
alert(newMso);
return newMso;
}
Result after run Script B
.
.
C) Javascript (Just changing HREF property A tag)
In this case you can simply use below jquery code:
$(document).ready(function(){
var webAddress="http://www.example.com";
$("div#mybtn").find('a:first').prop("href",webAddress);
});
Result after run Script C

Related

Refresh div with button click using random javascript string element

There are several similar questions, so I hope this is a unique problem. None of the proposed solutions on those similar questions have solved my issue. Humble apologies from this beginner if I messed up somehow.
I have an empty div on my page with I am loading using javascript with strings from an array. Currently, I have a script running on a button which reloads the entire page. I would like for that button to just reload the div with items from my javascript array.
Here is my code:
<html>
<head>
<link rel="stylesheet" href="obliqueStyle.css">
<style></style>
</head>
<link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
<body>
<div id="wrapper">
<div id="strategyBox"></div>
<div id="button">
<a class="againbutton" onclick="buttonReload()">Again</a>
<script>
var buttonReload = function() {
document.getElementById("strategyBox").innerHTML = '<p id="strategyText">' + randomStrategy + '</p>';
}
</script>
</div>
</div>
<script src="os.js"></script>
</body>
Here is a snippet of my array and the JS (coming from the os.js file referenced in index.html) I am using to load the div initially/on refresh:
var obliqueStrategy = ["Abandon normal instruments",
"Accept advice",
"Accretion",
"A line has two sides"];
var randomStrategy = obliqueStrategy[Math.floor(Math.random() * obliqueStrategy.length)];
document.getElementById("strategyBox").innerHTML = '<p id="strategyText">' + randomStrategy + '</p>';
I've tried calling the same javascript as a function in script in the html like this:
<div id="button">
<a class="againbutton" onclick="buttonReload()">Again</a>
<script>
var buttonReload = function() {
document.getElementById("strategyBox").innerHTML = '<p id="strategyText">' + randomStrategy + '</p>';
}
</script>
</div>
I've tried using the jQuery AJAX load function like this:
<script>
$(function() {
$("#againbutton").on("click", function() {
$("#strategyBox").load("index.html")
return false;
})
})
</script>
I've played around with variations of the above and tried a couple other things that I'm forgetting exactly how and what I did, so I can't include them. I've really hit a wall on this even though it seems profoundly simple.
Thanks in advance for any help.
Here's one method: http://jsfiddle.net/kxqcws07/
HTML
<div id="wrapper">
<div id="strategyBox"><p id="strategyText"></p></div>
<div>
<input type="button" class="againbutton" value="Again">
</div>
</div>
Javascript
//wrapping your logic in a namespace helps reduce the chances of naming collisions of functions and variables between different imported js files
var localNameSpace = function() {
//private array containing our strings to randomly select
var obliqueStrategy = [
"Abandon normal instruments"
, "Accept advice"
, "Accretion"
, "A line has two sides"
];
var api = {
//bindButtonAction binds the generateRandomStrategy function to the click event of the againbutton
bindButtonAction: function() {
$('#wrapper .againbutton').click(api.generateRandomStrategy);
}
, generateRandomStrategy: function() {
//get the position of one of the string randomly
//Math.random() returns a float value < 1 so multiplying it by 100 gets us a range of (0.* - 99.*)
//then we Math.floor() that to get rid of the float value and keep just the integer part
//finally we modulus it with the length of the string array
//if you are unfamiliar with modulus, what it does is gives you the remainder of a division. for instance 10 / 3 gives you 3 with a remainder of 1, so 10 % 3 would be just 1.
//what this does for us is keeps the random offset of our within the bounds of the array length (0 to length -1)
var randomOffset = Math.floor(Math.random() * 100) % obliqueStrategy.length;
//finally once we have the offset, we set the html to the string at the position in the array
$('#wrapper #strategyBox #strategyText').html( obliqueStrategy[randomOffset] );
}
};
return api;
}();
$(document).ready(function() {
//here we call the bind action so the button will work, but we also explicitly call the generateRandomStrategy function so the page will preload with a random string at the start
localNameSpace.bindButtonAction();
localNameSpace.generateRandomStrategy();
});

adding piece of HTML code using JS based on URL accessed

What I am trying to achieve is if a particular page is loaded in the browser for e.g www.domain.com/page then the following piece of code should be added in the page dynamically using JS (similar to how we load the Google Analytics code)
<div id="something">
<img src="http://domain.com/images/someImage.jpg">
</div>
I am trying to figure the script which will load the above mentioned HTML code (anywhere of the page - www.domain.com/page)
Edit 1:
what I am trying to achieve is when the user goes to www.domain.com/page.html I am calling another page lets say page1.html which should contain the script which insert the HTML code I posted above. So I simply want to insert the function which should be enclosed in the tag inside page1.html. Unfortunately I can not edit www.domain.com/page.html
If you want to PLACE that code anywhere in your page using javascript, you first need to identify that PLACE in DOM Using an "id" attribute. Here's an example:
HTML:
<html>
<body>
<div id="target1"></div>
<div id="target2"></div>
</body>
</html>
JS:
var html = '<div id="something"><img src="http://domain.com/images/someImage.jpg"></div>';
document.getElementById('target1').innerHTML = html;
document.getElementById('target2').innerHTML = html;
You can try something like this :
$(document).ready(function () {
var url = window.location.href;
$("#something").append("<img src='"+ url +"' />");
});
$(".documentholder").load("code.html");
If you a specific id of something
$(".documentholder").load("code.html #someid");
If you a specific tag and id of something
$(".documentholder").load("code.html #someid");
Here you are,
just change this part if (getFileName() == "js") with if (getFileName() == "page")
I added js because that is what is returning in the code snippet :)
function getFileName() {
var url = document.location.href;
url = url.substring(0, (url.indexOf("#") == -1) ? url.length : url.indexOf("#"));
url = url.substring(0, (url.indexOf("?") == -1) ? url.length : url.indexOf("?"));
url = url.substring(url.lastIndexOf("/") + 1, url.length);
return url;
}
var div = '<div id="something"><img src="http://domain.com/images/someImage.jpg"></div>';
if (getFileName() == "js") {
$('body').append(div);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
let's say you save this code in a html-file named something.html
$(".documentholder").load("something.html");
in this case the class "documentholder" is the container you put the code in

How do I replace an HTML button with several images using javascript?

I currently have:
//javascript
function morshots()
{
var mordor = document.getElementById("ss1");
var shots= (
mordor.innerHTML = <img src="http://i.imgur.com/83HCt.png" alt="scrns1"><img src="http://i.imgur.com/5mWIy.png" alt="scrns2"><img src="http://i.imgur.com/pPafl.png" alt="scrns3">;
}
and
<!--html-->
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="screenshots.js"></script>
</head>
<body>
<div id="ss1">
<button onClick="morshots();">View Screenshots</button>
</div>
</body>
</html>
Currently the button does nothing on click. What I want is for the images to replace the button on the page. This is not my entire code, however I omitted the non-pertinent piece of code for readability.
--EDIT--
I have added escapes for the inner quotes and non-escaped quotes around the image tags. I am still getting the same result with the page (button click does nothing)
function morshots()
{
var mordor = document.getElementById("ss1");
mordor.innerHTML = '<img src=\"http://i.imgur.com/83HCt.png\" alt=\"scrns1\"><img src=\"http://i.imgur.com/5mWIy.png\" alt=\"scrns2\"><img src=\"http://i.imgur.com/pPafl.png\" alt=\"scrns3\">';
}'
---EDIT2:----
Fixed it, the working code reads:
function morshots()
{var mordor = document.getElementById("ss1");
mordor.innerHTML = '<img src=\"http://i.imgur.com/83HCt.png\" alt=\"scrns1\"><img src=\"http://i.imgur.com/5mWIy.png\" alt=\"scrns2\"><img src=\"http://i.imgur.com/pPafl.png\" alt=\"scrns3\">';
}
Add the <img>s within quotes:
function morshots()
{
var mordor = document.getElementById("ss1");
mordor.innerHTML = '<img src="http://i.imgur.com/83HCt.png" alt="scrns1"><img src="http://i.imgur.com/5mWIy.png" alt="scrns2"><img src="http://i.imgur.com/pPafl.png" alt="scrns3">';
}
Did you check your JavaScript console for errors?
// syntax error:
var shots= (
// syntax error:
mordor.innerHTML = <img src="http://i.imgur.com/83HCt.png" alt="scrns1"><img src="http://i.imgur.com/5mWIy.png" alt="scrns2"><img src="http://i.imgur.com/pPafl.png" alt="scrns3">;
You need to pass a string to mordor.innerHTML - wrap your html in quotes. I'm not sure what you're trying to do with shots.
Add quotes and escape them withing html adding backslash \ before them:
var mordor = document.getElementById("ss1");
mordor.onclick = function () {
var shots= "<img src=\"http://i.imgur.com/83HCt.png\" alt=\"scrns1\"><img src=\"http://i.imgur.com/5mWIy.png\" alt=\"scrns2\"><img src=\"http://i.imgur.com/pPafl.png\" alt=\"scrns3\">";
mordor.innerHTML = shots;
};

Accessing inline CSS properties using getElementsByClassName

I have this piece of HTML code.
<div class="tagWrapper">
<i style="background-image: url(https://fbcdn-photos-a.akamaihd.net/hphotos-ak-ash4/390945_10150419199065735_543370734_8636909_2105028019_a.jpg);"></i>
</div>
I need to get that url within the brackets. I tried using the getElementsByClassName() method but it didn't work. Since url is not a HTML element, I have no idea on how to take out the value. I can't use getElementById(), because I can't add an id to the HTML (it's not mine). It needs to work in Chrome and Firefox. Any suggestions?
You didn't add a jQuery tag, so here's a native solution (note that this likely won't work on older versions of IE, but you said it only has to work on Chrome and FF):
var origUrl = document.getElementsByClassName("tagWrapper")[0]
.children[0].style.backgroundImage;
var url = origUrl.substr(4, origUrl.length - 5);
Or
var url = origUrl.replace("url(", "").replace(")", "");
Here's a fiddle
EDIT
Answering your comment
document.getElementsByClassName("tagWrapper")
gets all elements with the class name tagWrapper. So to get the first one, you grab the zero index
document.getElementsByClassName("tagWrapper")[0]
Then you want the first child under there, and the backgroundImage property on this first child.
document.getElementsByClassName("tagWrapper")[0]
.children[0].style.backgroundImage;
From there it's a simple matter stripping the url( and ) from it
var url = origUrl.substr(4, origUrl.length - 5);
or
var url = origUrl.replace("url(", "").replace(")", "");
You can use querySelector():
Demo: http://jsfiddle.net/ThinkingStiff/gFy6R/
Script:
var url = document.querySelector( '.tagWrapper i' ).style.backgroundImage;
url = url.substr(4, url.length - 5);
If you where using jquery you could do something like this
$(".tagWrapper i").css("background-image")
I think if you use jQuery it will be easer.
var w = document.getElementsByClassName('tagWrapper')[0];
for (var i=0; i<w.childNodes.length; i++)
if (w.childNodes[i].tagName && w.childNodes[i].tagName.toLowerCase() == 'i')
return w.childNodes[i].style.backgroundImage;
<div class="tagWrapper">
<i id="something" style="background-image: url(https://fbcdn-photos-a.akamaihd.net/hphotos-ak-ash4/390945_10150419199065735_543370734_8636909_2105028019_a.jpg);"></i>
</div>
// script / without jQuery
var url = document.getElementById('something').style.backgroundImage.match(/\((.*?)\)/)[1];
Use jQuery!!!
$("div.tagWrapper i").css("background-image").substr(4, $("div.tagWrapper i").css("background-image").length-5)
Example
If You don't have to care about Microsoft browsers, the raw JavaScript is quite easy. You can use getElementsByClassName and getElementsByTagName, however it is easier to try querySelectorAll. I've included both. The use of regular expression preserve relative links.
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script type='text/javascript'>
var do_find_a = function() {
var tmp = document.getElementsByClassName('tagWrapper')[0];
var tst = tmp.getElementsByTagName('i')[0].getAttribute('style');
return do_alert(tst);
}
var do_find_b = function() {
var tst = document.querySelectorAll('.tagWrapper i')[0].getAttribute('style');
return do_alert(tst);
}
var do_alert = function(tst) {
var reg = /background-image:\s*url\(["']?([^'"]*)["']?\);?/
var ret = reg.exec(tst);
alert (ret[1]);
return;
}
document.addEventListener('DOMContentLoaded',do_find_a,false);
document.addEventListener('DOMContentLoaded',do_find_b,false);
</script>
</head>
<body>
<div class='tagWrapper'>
<i style='background-image: url("http://example.com/image.jpg");'></i>
</div>
Text to ignore.
</body>
</html>
And jsFiddle version:
http://jsfiddle.net/hpgmr/

How to change the innerHTML of a div in the main page according to the div value in the included page?

I have included a file named test.php in the file index.php
lets assume index.php is like this
<html>
<head>
</head>
<body>
<h1 id="dash">Index</h1>
<div id='tab.php'>
<?php include('tab.php'); ?>
</div>
</body>
</html>
and tab.php is like this
<html>
<head>
</head>
<body>
<ul>
<li id='date' onClick="change_head(this.id);">Dates</li>
<li id='appoint' onClick="change_head(this.id);">Appointments</li>
<ul>
</body>
</html>
Here what i would like to do is, if the list item date is clicked(list items are actually tabs). The inner html of the h1 tag with id dash should be changed to Dates and if the list item appoint is clicked the inner html of same h1 tag with id dash should change to appointments.
how can i do that ?? i tried the usual javascript way by taking the ids and applying the if condition to change the innerHTML but it was not working..anyone pls help me how to do it
JAVASCRIPT (this is the js i tried to achive it...i added this in index.php)
function change_head(id){
dash = document.getElementById('dash').innerHTML;
if(id == date){
dash = "Date";
}
else if(id == appoint){
dash = "Appointment";
}
else{
dash = "Index";
}
}
You could try using jquery... something like this:
<script type="text/javascript">
$(document).ready(function () {
$("li#date").click(function () {
$("h1#dash").val("Dates");
});
$("li#appoint").click(function () {
$("h1#dash").val("Appointments");
});
});
</script>
Of course, if you had more of these tabs, I would create a single click event handler for all "li" elements and switch on the ID :-)
Assuming you're new to jquery, you'd also have to include the jquery script in your page. Something like:
<script src="/Scripts/jquery-1.6.4.min.js" type="text/javascript"></script>
Check out jquery.com to get started.
If you want do it with JavaScript (i.e. without page reloading), so you need use DOM innerHTML.
Something like (if you didn't use jQuery), didn't test this code through, hope you get idea:
var changetext = function(e,t) {
e.innerHTML = t;
},
elemheader = document.getElementById('dash'),
elemdate = document.getElementById('date'),
elemappoint = document.getElementById('appoint');
if (elemdate.addEventListener) {
elemdate.addEventListener('click',changetext(elemheader,'Date'),false);
}
if (elemappoint.addEventListener) {
elemappoint.addEventListener('click',changetext(elemheader,'Appoint'),false);
}

Categories

Resources