use javascript to insert google ads within a page of text - javascript

I am trying to insert google ads after the first paragraph of the text box on my mediawiki site. My code is based on https://www.mediawiki.org/wiki/Extension:AdsWherever.
I have a function that returns a tag which will render the google ads code.
I am using javascript to check if the tag is there, if it isn't I'm inserting it after the first paragraph.
The issue is none of the rest of the text in the text box is showing after the google ads. I think this may because the function is returning a value and breaking out of the code and so not allowing the rest of the javascript code to run. (I may be wrong but this is what I think the issue is).
How do I insert the google ads in the correct place and still show the text after the ads?
I don't mind skipping the function altogether and just using javascript to insert the code but I don't know how to write the javascript so var b contains the javascript for the google ads.
This is my code:
$wgHooks['ParserFirstCallInit'][] = 'AdsSetup';
$wgHooks['EditPage::showEditForm:initial'][] = 'CheckHasTag';
function AdsSetup( &$parser ) {$parser->setHook( 'ads', 'AdsRender' ); return true;}
function AdsRender($input, $args ) {
$input =""; $url = array(); global $wgOut;
$ad['goo1'] = '<html><br><script type="text/javascript">
google_ad_client = "xxx";
google_ad_width = 728;
google_ad_height = 90;
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script><br></html>';
$media = $args['media'];
return $ad[$media];
}
// check if content has <goo1> tag
function CheckHasTag($editPage){
global $wgOut;
$wgOut->addScript('<script type="text/javascript">
var editTextboxText = document.getElementById("wpTextbox1").value;
var searchFor = "goo1";
var searchResult = editTextboxText.search(searchFor);
if(searchResult == -1){
var a = editTextboxText;
var b = "\n<ads media=goo1>\n";
var findP = "\n";
var p = editTextboxText.search(findP);
var position = p;
document.getElementById("wpTextbox1").value = a.substr(0, position) + b + a.substr(position);
}
</script>');
return true;
}

var editTextboxText = document.getElementById("mw-content-text").innerHTML;
var searchFor = new RegExp("goo1");
if (searchFor.test(editTextboxText) === false) {
var ad = document.createElement('ads');
ad.setAttribute('media', 'goo1');
var parent = document.getElementById("mw-content-text").getElementsByTagName('p')[0].parentNode;
var secondParagraph = document.getElementById("mw-content-text").getElementsByTagName('p')[0].nextSibling;
parent.insertBefore(ad, secondParagraph);
}
JSfiddle

Related

Adding a picture to a html printout using javascript

I have a sharepoint webpart I am printing using the script below.
The problem is I need to add a a picture to the header of the page it prints that is located at an address. I am trying to modify this but I don't have alot of javascript experience not sure what the syntax is.
Also I would like to specify the image to a specific size and center it is that possible?
I am aware the src is set to "url" I just don't want to share my actual link on here.
<center>
<input onclick="javascript:void(PrintWebPart())" type="button" value="Print Proof of Pricing"/>
</center>
<script language="JavaScript">
//Controls which Web Part or zone to print
var WebPartElementID = "ctl00_ctl34_g_db6615a7_4c3b_4a14_9bbc_43ce9d63c24d_FormControl0";
var d= new Date();
var elem = document.createElement("img");
elem.setAttribute("src", "url");
elem.setAttribute("height", "768");
elem.setAttribute("width", "1024");
elem.setAttribute("alt", "Tag");
elem.setAttribute("align", "middle");
//Function to print Web Part
function PrintWebPart()
{
var bolWebPartFound = false;
if (document.getElementById != null)
{
//Create html to print in new window
var PrintingHTML = '<HTML>\n<HEAD>\n';
//Take data from Head Tag
if (document.getElementsByTagName != null)
{
var HeadData= document.getElementsByTagName("HEAD");
if (HeadData.length > 0)
PrintingHTML += HeadData[0].innerHTML;
}
PrintingHTML += '\n</HEAD>\n<BODY>\n';
var WebPartData = document.getElementById(WebPartElementID);
if (WebPartData != null)
{
PrintingHTML +='<div id="imageDiv">\n</div>\n'
PrintingHTML += WebPartData.innerHTML;
PrintingHTML += "Pricing Date: " +d;
bolWebPartFound = true;
}
else
{
bolWebPartFound = false;
alert ('Cannot Find Web Part');
}
}
PrintingHTML += '\n</BODY>\n</HTML>';
//Open new window to print
if (bolWebPartFound)
{
var PrintingWindow = window.open("","View Proof of Pricing",
"toolbar,width=800,height=600,scrollbars,resizable,menubar");
PrintingWindow.document.open();
PrintingWindow.document.write(PrintingHTML);
PrintingWindow.document.getElementById("imageDiv").appendChild(elem);
// Open Print Window
}
}
</script>
I believe you can set the image as background to "imageDiv" as
document.getElementById("imageDiv").style["background"]="url(***YOUR_URL***) no-repeat center center";
Note: You do need to give a height to the container as per your need, say
document.getElementById("imageDiv").style["min-height"]="300px";

Using javascript Not able to disable textbox.It Immediatly enable after disabled. Can anyone give me solution?

I have One simple registration Form which is developed in C#.Net. This form also contain one Grid view which display data from database.In this,I want to disable Insert button when i select particular raw data. and i had develop this code in jquery. I used below code.
function DoStuff(lnk) {
debugger;
var grid = document.getElementById('GridView1');
var cell, row, rowIndex, cellIndex;
cell = lnk.parentNode;
row = cell.parentNode;
rowIndex = row.rowIndex;
cellIndex = cell.cellIndex;
var rowId = grid.rows[rowIndex].cells[0].textContent;
var rowname = grid.rows[rowIndex].cells[1].textContent;
var rowcontact = grid.rows[rowIndex].cells[2].innerHTML;
var rowaddress = grid.rows[rowIndex].cells[3].innerHTML;
var rowemail = grid.rows[rowIndex].cells[4].innerHTML;
var Id = document.getElementById('txt_Id');
var name = document.getElementById('txt_Name');
var contact = document.getElementById('txt_PhoneNumber');
var address = document.getElementById('txt_Address');
var email = document.getElementById('txt_EmailId');
Id.value = rowId;
name.value = rowname;
contact.value = rowcontact;
address.value = rowaddress;
email.value = rowemail;
document.getElementById('Button1').disabled = true;
};
But when i run that page it becomes disable and immediately enable automatically.....:(
Can anyone give me solution ???
You have to call this function after form is completely loaded.
Use below code to make it that happen if you are using jQuery.
$( document ).ready(function() {
DoStuff(lnk);
});

Change existing javascript Ticker to work from RSS feed

I am not good at code so am a bit in the hands of anyone who might be able to help.
I have a functioning Ticker Tape working in my wordpress site here www.solosails.com
currently, it works from data manually entered, I would like to modify it so that it takes the title and link from my RSS feed myurl/feed hopefully by using something like this ...
$.get(FEED_URL, function (data) {
$(data).find("entry").each(function () { // or "item" or whatever suits your feed
var el = $(this);
console.log("------------------------");
console.log("title : " + el.find("title").text());
console.log("author : " + el.find("author").text());
console.log("description: " + el.find("description").text());
});
});
The Java Script code is...
function startTicker(){theCurrentStory=-1;theCurrentLength=0;if(document.getElementById){theAnchorObject=document.getElementById("tickerAnchor");runTheTicker()}else{document.write("Error");return true}}function runTheTicker(){var e;if(theCurrentLength==0){theCurrentStory++;theCurrentStory=theCurrentStory%theItemCount;theStorySummary=theSummaries[theCurrentStory];theTargetLink=theSiteLinks[theCurrentStory];theAnchorObject.href=theTargetLink}theAnchorObject.innerHTML=theStorySummary.substring(0,theCurrentLength)+whatWidget();if(theCurrentLength!=theStorySummary.length){theCurrentLength++;e=theCharacterTimeout}else{theCurrentLength=0;e=theStoryTimeout}setTimeout("runTheTicker()",e)}function whatWidget(){if(theCurrentLength%2==1){return theWidgetOne}else{return theWidgetNone}}
This is the part of the code that potentially needs altering so that the hardcoded links and titles become the new code pulling from the rss feed...
var theCharacterTimeout = 50;
var theStoryTimeout = 4000;
var theWidgetOne = "_";
var theWidgetNone = "";
var theSummaries = new Array();
var theSiteLinks = new Array();
var theItemCount = 2;
theSummaries[0] = "Solo Sails proudly sponsor Lizzy Foremans Mini Transat Campaign... Read more here ...";
theSiteLinks[0] = "http://www.solosails.com/solo-sails-sponsor-lizzie-foremans-mini-transat-campaign/"
theSummaries[1] = "10% discounts on ALL multiple sail orders !! Try us for price with your new sails, complete our simple quote form here.";
theSiteLinks[1] = "http://www.solosails.com/quotes"
startTicker();
Many thanks in advance if you can help!
Andrew
Still hoping somebody can help here.
I basically want to either get theSummaries and theSiteLinks to be pulled from the rss or change the arrays so that they use the XML parser in Javascript.
Would really appreciate some help here and happy to donate something via paypal for the working result.
Regards, Andrew
Thanks to #David Hammond for finding the answer ...
var theCharacterTimeout = 75;
var theStoryTimeout = 4000;
var theWidgetOne = "_";
var theWidgetNone = "";
var theSummaries = new Array();
var theSiteLinks = new Array();
jQuery.get('http://www.solosails.com/feed/', function(data) {
var $xml = jQuery(data);
$xml.find("item").each(function() {
var $this = jQuery(this),
item = {
title: $this.find("title").text(),
link: $this.find("link").text()
}
//Do something with item here...
theSummaries.push(item.title);
theSiteLinks.push(item.link);
});
theItemCount = theSummaries.length;
startTicker();
});

Hover over data using title attribute in javascript

I have a javascript code that displays data in a table format and when hovered over the first column it displays additional details. The hover over code is using jquery tooltip and the title attribute of html. The code works fine in most cases but if one of the fields I am displaying in the hover has " symbol it screws up everything that record onwards and the hover and main data display together and the hover doesnt work on those rows.
below is a snapshot of my code
var medicationName = medJSON.MED_DETAILS[medIdx1].ORDER_NAME;
var orderdetails = medJSON.MED_DETAILS[medIdx1].ORD_DETAILS;
var comments = medJSON.MED_DETAILS[medIdx1].ORD_COMMENTS;
var reqStart = medJSON.MED_DETAILS[medIdx1].REQ_ST_DT;
var originalStart = medJSON.MED_DETAILS[medIdx1].ORIG_ORD_DT;
var lastDose = medJSON.MED_DETAILS[medIdx1].LAST_DOSE;
var nextDose = medJSON.MED_DETAILS[medIdx1].NEXT_DOSE;
var stopDt = medJSON.MED_DETAILS[medIdx1].STOP_DT_TM;
var stopReason = medJSON.MED_DETAILS[medIdx1].STOP_REASON;
var enteredBy = medJSON.MED_DETAILS[medIdx1].ORDER_ENTERED_BY;
var status = medJSON.MED_DETAILS[medIdx1].ORD_STATUS;
var simpleDetails = medJSON.MED_DETAILS[medIdx1].CLIN_DISP_LN;
if(nextDose.length == 0)
{
nextDose = "Not Defined";
}
var medHover = ["<table><tr><td><b>Medication:</b></td><td>",medicationName,"</td></tr>"
,"<tr><td><b>Details:</b></td><td>",simpleDetails,"</td></tr>"
//,"<tr><td><b>Order Comments:</b></td><td>",comments,"</td></tr>"
,"<tr><td><b>Request Start:</b></td><td>",reqStart,"</td></tr>"
,"<tr><td width = 200px><b>Original Order Date/Time:</b></td><td>",originalStart,"</td></tr>"
,"<tr><td><b>Last Documented Dose:</b></td><td>",lastDose,"</td></tr>"
,"<tr><td><b>Next Scheduled Dose:</b></td><td>",nextDose,"</td></tr>"
,"<tr><td><b>Stop Date/Time:</b></td><td>",stopDt,"</td></tr>"
,"<tr><td><b>Stop Reason:</b></td><td>",stopReason,"</td></tr>"
,"<tr><td><b>Order Entered By:</b></td><td>",enteredBy,"</td></tr>"
,"<tr><td><b>Status:</b></td><td>",status,"</td></tr>"
,"</table>"]
tempStr1.push("<tr class = 'evenrow' ><td class = 'cmedname custhvr' title=\"",medHover.join(""),"\">",medicationName,"</td><td> ",simpleDetails,"</td></tr>")
thanks,
Sid
Process medHover with:
medHover.join("").replace('\"', '"');
This replaces the quote character with a value usable with HTML.

is there a way to use javascript or jquery to add a color to the search keyword

the url is like this:
http://www.example.com/index.php?main_page=advanced_search_result&keyword=Sons+of+Anarchy
on the above the search keyword is Sons of Anarchy. now, is there a way to add a color to the keyword when in the search result content with js on the search result page . thank you.
ps:the search input box:<input type="text" class="keybg" id="keyword" name="keyword">
$sData['pfrom'] = (isset($_GET['pfrom']) ? zen_output_string($_GET['pfrom']) : '');
$sData['pto'] = (isset($_GET['pto']) ? zen_output_string($_GET['pto']) : '');
the above way is added a parameter to the url.
http://www.example.com/index.php?main_page=advanced_search_result&keyword=Sons+of+Anarchy&pfrom=...pto=..
You could do something like this:
document.body.innerHTML = document.body.innerHTML.replace(/Anarchy/ig, '<mark>Anarchy</mark>');
Try this (this assumes you are loading jQuery into the page):
myFile.php
==========
<?php
$sData['pfrom'] = (isset($_GET['pfrom'])
? zen_output_string($_GET['pfrom'])
: '');
$sData['pto'] = (isset($_GET['pto'])
? zen_output_string($_GET['pto'])
: '');
// ... your other code here
?>
<!-- PUT THIS SCRIPT AT THE END OF YOUR HTML BODY ELEMENT -->
<script type="text/javascript">
// get the current URL
var url = window.location.toString();
//get the parameters
url.match(/\?(.+)$/);
var params = RegExp.$1;
// split up the query string and store in an
// associative array
var params = params.split("&");
var queryStringList = {};
for (var i=0;i<params.length;i++) {
var tmp = params[i].split("=");
queryStringList[tmp[0]] = unescape(tmp[1]);
}
// get the body html and update it to have keyword colored
var searchKeyword = queryStringList.keyword;
var searchRegex = new Regexp('/'+searchKeyword+'/', 'gi');
var html = $('body').html();
var coloredHTML = html
.replace(searchRegex,
"<span style="color:green">"+html+"</span>");
$('body').html(coloredHTML);
</script>
I think what you want is something like this.
The solution will not mess up your html if you are searching for something that is probably inside html tags, e.g., span
The search key will be escaped in order to generate a correct reg exp object
code:
var searchKey = 'rray($';
highlight(searchKey, $('div'));
searchKey = '|| !';
highlight(searchKey, $('div'));
function highlight(word, $target){
var conts = $target.html().split('<').join('><').split('>');
var escapeRgx = /([\/\.\*\+\?\|\(\)\[\]\{\}\\\:\$\^])/g;
var searchRgx = new RegExp(word.replace(escapeRgx, '\\$1'), 'gi');
$.each(conts, function(idx, str){
if(str.charAt(0) != '<'){
conts[idx] = str.replace(searchRgx, '<span class="mark">' + word + '</span>') ;
} else {
conts[idx] = str + '>';
}
});
$target.html(conts.join(''));
}
For getting the search key, you can retrieve it at the backend, and echo it to the frontend. i.e.,
<? echo 'var searchKey = "'. $_GET['key'] .'"'; ?>
Here is the demo -
http://jsfiddle.net/jn7TC/4/

Categories

Resources