JavaScript : display Google ad conditionally - javascript

I want to display google ads at vbulletin forum when the thread not contains any crack or serial so I write this code:
<div id ="d_content"> post goes here...</div>
<div id="adv_content"></div>
<script>
function isBlank(str) {
return (!str || /^\s*$/.test(str));
}
var str = document.getElementById("d_content").innerHTML;
var pattern = /crack|nulled|serial|register|key|pach|patch/gi;
var Len= str.match(pattern);
if( isBlank(Len) ) document.write("adv..");
</script>
but how to put the google ad code instead of "adv.."
this is my try :
<div id ="d_content"> post goes here...</div>
<div id="adv_content"></div>
<script>
function isBlank(str) {
return (!str || /^\s*$/.test(str));
}
var str = document.getElementById("d_content").innerHTML;
var pattern = /crack|nulled|serial|register|key|pach|patch/gi;
var Len= str.match(pattern);
if( isBlank(Len) ) document.write("
<script type="text/javascript"><!--
google_ad_client = "ca-pub-1564912551365218";
/* 728x90, تم إنشاؤها 02/06/11 زهير طه */
google_ad_slot = "7785253845";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
");
</script>
but not worked..

Your code is not going to work because browsers will interpret the first </script> as the end of your script, eve though it is within a text string.
A workaround is to use an escape/unescape sequence:
document.write(unescape("%3Cscript type='text/javascript'%3E[your script here]%3C/script%3E"));
where < is escaped as %3C and > is escaped as %3E.

Related

The problem of finding div class number with jquery

I would like to find a number of div classes and add a code after class two.
UPDATE
It works just as it should when writing another code instead of Google ad codes.
<script>
$(function()
{
var say = $('.panel-footer.clearfix').length;
if(say >= 3){
$('.panel-footer.clearfix')[1].after('<script async
src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<ins class="adsbygoogle"
style="display:inline-block;width:320px;height:100px"
data-ad-client="ca-pub-3767785488130692"
data-ad-slot="3213073317"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>');
}
});
but it doesn't work. The code is running at the bottom of the page instead of the number two div.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="panel-footer clearfix"></div>
<div class="panel-footer clearfix"></div>
<div class="panel-footer clearfix"></div>
<script>
function insert_adsbygoogle(arg1) {
//https://support.google.com/adsense/answer/7477845?hl=en
(window.adsbygoogle = window.adsbygoogle || []).push({
google_ad_client: "ca-pub-3767785488130692",
data_ad_slot: "3213073317",
enable_page_level_ads: true
});
var say = $('.panel-footer.clearfix').length;
if (say >= 3) {
$('.panel-footer.clearfix').eq(1).after("<div id=write_container_for_adsbygoogle></div>");
// container is where you want the ad to be inserted
var script = document.createElement("script");
script.type = "text/javascript";
script.setAttribute("async", "");
script.src = "//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js";
$('#write_container_for_adsbygoogle').after(script);
} else if (arg1 === "first") {
$(window).on("load", insert_adsbygoogle);
}
}
insert_adsbygoogle("first");
</script>
Aussuming that clearfix is class name
<script>
$(function()
{
var say = $('.panel-footer.clearfix').length();
if(say >= 3){
$('.panel-footer.clearfix:eq(2)').after('<?php echo
get_option("my_php_code");?>');
}
});
</script>
You can achieve this by using the indexation of the array returned by jquery, also length is not a function so it's just length.
$(function()
{
var say = $('.panel-footer clearfix').length;
if(say >= 3){
$('.panel-footer clearfix')[1].after('<?php echo get_option("my_php_code");?>');
}
});
If clearfix is a class you must use: $('.panel-footer.clearfix') as remarked in another comment.

script with the phone number to be replaced for that page

So I tried this. I put the required code in the head:
<script type="text/javascript">
var callback = function(formatted_number, mobile_number) {
var e = document.getElementById("number");
e.innerHTML = "";
e.appendChild(document.createTextNode(formatted_number));
};
</script>
And then instead of using:
<body onload="_googWcmGet(callback, '0800-123-4567')">
<span id="number">0800-123-4567</span> </body>
I'm using:
<body> <span id="number">0800-123-4567</span> <script type="text/javascript">
window.onload = _googWcmGet(callback, '0800-123-4567'); </script> </body>
It errors out with _googWcmGet being undefined. Think this is due to my lack of knowledge of JS/DOM stuff and that I need to cal _googWcmGet outside the body tag some other way?

insert dynamically string containing script into HTML and executing it dynamically

I have a variable of the form :
var x = '<script type="text/javascript" language="javascript"> ..lots of stuff...</script>
<script type="text/javascript" language="javascript"> ..even more of stuff...</script>'
and I want to insert it with jquery into my HTML code and execute it.
I tried using the append, html and eval without any luck.
Any ideas?
sample script:
<script type="text/javascript" language="javascript">
var clk = 'http://......';
</script>
<script type="text/javascript" language="javascript" src="http://...."></script>
<noscript>
<img src="http://..." width="120" height="600" border="0" alt="">
</noscript>
this will in the end show an img, which will load asynchronously.
Usually having </script> tags nested within other <script></script> tags will break things. You'll need to split them up like in the Javascript below to not cause browser issues.
Here is a working fiddle:
https://jsfiddle.net/2vrfxrse/
Javascript
var jsCode = '<scr' + 'ipt>var executeTest = function(){ alert("This is a test."); }</scr' + 'ipt>';
$('head').append(jsCode);
HTML
<script>executeTest();</script>
This solution will probably work for your specific scenario:
var rx = new RegExp("<script .*?>(.*?)<\/script>", 'g');
var x = '<script type="text/javascript" language="javascript">alert("..lots of stuff...");</script><script type="text/javascript" language="javascript">alert("..even more of stuff...");</script>';
var res = rx.exec(x);
while (res) {
var s = document.createElement("script");
s.appendChild(document.createTextNode(res[1]));
document.body.appendChild(s);
res = rx.exec(x);
}
JSBin: http://jsbin.com/menocumiya/edit?html,js,console,output
You can use Jquery getScript:
//Moment example
if (typeof moment == "undefined") {
var url = "~/assets/js/moment.js";
$.getScript(url);
}
Or Jquery Function:
$(function(){
var test = "this.Foo = function() {alert('hi');}";
var F=new Function (test);
(new F()).Foo(); //Shows "Hi" alert
});
$(function(){
var test = "this.Foo = function() {alert('hi');}";
var F=new Function (test);
(new F()).Foo(); //Shows "Hi" alert
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

If else javascript statement

I have a code that i want to execute but dont know how to go about it. I have a page that you can convert between two languages, english and french. I want to run a script in my index.html.erb file only if the page is in french and not in English.
This code is at the beginning of my index.html.erb file.
<script>
var a = <%= params[:locale]%>
if(a == "fr")
{
<script type="text/javascript">
/* <![CDATA[ */
var google_conversion_id = 1001007867;
/* ]]> */
</script>
<script type="text/javascript" src="//www.googleadservices.com/pagead/conversion.js">
</script>
<noscript>
<div style="display:inline;">
</div>
</noscript>
}
</script>
I am not sure if my code is correct. Any help is appreciated.
you cant nest script tags, you could append a script tag if your condition is met, sth. like :
<script>
var a = <%= params[:locale]%>;
console.log(a) /* THIS REALLY LOGS THE EXPECTED VALUE ? */
if(a == "fr")
{
var google_conversion_id = 1001007867;
var bh = document.createElement('script'), s = document.getElementsByTagName('script')[0];
bh.type = 'text/javascript';
bh.src = '//www.googleadservices.com/pagead/conversion.js';
s.parentNode.insertBefore(bh, s);
}
</script>
<noscript>
<div style="display:inline;">
</div>
</noscript>
the better solutions would be if your templating-language e.g <%= %> supports if else conditions
check your browser console for errors

I am getting "Object Required" error message

I am trying to stick a news scroller on the home page of our website.
I am a bit confused by the error message I am getting because I get it on one PC but not on another:
Object Required
I am using the below code but the following line keeps throwing Object Required error when I use this file as a web user control on my default.aspx page:
el2.style.height='<%=box_height %>';
As a result, the news is not scrolling.
Any help greatly appreciated.
<uc1:NewsScroller ID="NewsScroller1" runat="server" />
<script language="VB" runat="server">
Public box_TextColor As String = "black"
Public box_height As Integer = 150
Public box_width As Integer = 166
Public box_padding As String = "0 0 0 20"
</script>
<script type="text/javascript" for="window" event="onload">
// <!CDATA[
return window_onload()
// ]]>
</script>
<script type="text/javascript">
// <!CDATA[
// <!--
var speed = 2;
function init(){
var el = document.getElementById("newsdiv");
el.style.overflow = 'hidden';
el.style.height='<%=box_height %>';
el.style.width='<%=box_width %>';
el.style.padding='<%=box_padding %>';
el.style.color='<%=box_TextColor %>';
var el2 = document.getElementById("newsdiv-p1");
el2.style.height='<%=box_height %>';
var el3 = document.getElementById("newsdiv-p2");
el3.style.height='<%=box_height %>';
//alert(document.getElementById("newsdiv-p2").style.height+document.getElementById("newsdiv-p2").style.height);
scrollFromBottom();
}
var go = 0;
var timeout = '';
function scrollFromBottom(){
clearTimeout(timeout);
var el = document.getElementById("newsdiv");
if(el.scrollTop >= el.scrollHeight-'<%=box_height %>'){
el.scrollTop = 0;
};
el.scrollTop = el.scrollTop + speed;
if(go == 0){
timeout = setTimeout("scrollFromBottom()",50);
};
}
function stop(){
go = 1;
}
function startit(){
go = 0;
scrollFromBottom();
}
// -->
function window_onload() {
init();
}
// ]]>
</script>
<%--<asp:Panel ID="newsdiv" runat="server" onmouseout="startit();" onmouseover="stop();">--%>
<div id="newsdiv" onmouseout="startit();" onmouseover="stop();" >
<p id="newsdiv-p1" class="spacer"></p>
<asp:Label ID="lblNews" runat="server" Text="News..."></asp:Label>
<p id="newsdiv-p2" class="spacer"></p>
</div>
<%--</asp:Panel>--%>
#Marcel, I suppose you mean the source (right-click, view source and copy the code)?
If so, here it is and again, thanks
<script type="text/javascript" for="window" event="onload">
// <!CDATA[
return window_onload()
// ]]>
</script>
<script type="text/javascript">
// <!CDATA[
// <!--
var speed = 2;
$(document).ready(function init(){
var el = document.getElementById("newsdiv");
el.style.overflow = 'hidden';
el.style.height='150';
el.style.width='166';
el.style.padding='0 0 0 20';
el.style.color='black';
var el2 = document.getElementById("newsdiv-p1");
el2.style.height='150';
var el3 = document.getElementById("newsdiv-p2");
el3.style.height='150';
//alert(document.getElementById("newsdiv-p2").style.height+document.getElementById("newsdiv-p2").style.height);
scrollFromBottom();
});
var go = 0;
var timeout = '';
function scrollFromBottom(){
clearTimeout(timeout);
var el = document.getElementById("newsdiv");
if(el.scrollTop >= el.scrollHeight-'150'){
el.scrollTop = 0;
};
el.scrollTop = el.scrollTop + speed;
if(go == 0){
timeout = setTimeout("scrollFromBottom()",60);
};
}
function stop(){
go = 1;
}
function startit(){
go = 0;
scrollFromBottom();
}
// -->
function window_onload() {
init();
}
// ]]>
</script>
<div id="newsdiv" onmouseout="startit();" onmouseover="stop();" >
<p id="newsdiv-p1" class="spacer">
</p>
<span id="NewsScroller1_lblNews"><a href='#' OnClick=javascript:window.open('newsDetail.aspx?NewsID=10','NewsDetail','width=800,height=600;toolbar=no;');><font face='verdana' size='2' color='#184D68'>Steve's Birthday</font><br><br><a href='#' OnClick=javascript:window.open('newsDetail.aspx?NewsID=15','NewsDetail','width=800,height=600;toolbar=no;');><font face='verdana' size='2' color='#184D68'>Our Anniversary</font><br><br><a href='#' OnClick=javascript:window.open('newsDetail.aspx?NewsID=14','NewsDetail','width=800,height=600;toolbar=no;');><font face='verdana' size='2' color='#184D68'>Jessie's Birthday</font><br><br></span>
<p id="newsdiv-p2" class="spacer"></p>
</div>
I am still trying to wrap my head on how this great forum works. Yesterday, I was able to see a button that says, "Add comment". Since today, I have not been able to see it. I guess my question is, how do you log back in so you are able to add comments, etc? Login appears to be cookie-driven which means that your priviledges disappear once you close the browser, no?
In this case, the error message ‘Object required’ means that variable el2 doesn't contain an HTMLElement object.
ID's of elements are case-sensitive, so you can't get the element
<p id="newsdiv-p1" class="spacer"></p>
using
var el2 = document.getElementById("newsDiv-p1");
Moreover, you can't access elements that have not been rendered yet. Put your function in an onload handler or after the markup.
BTW, the language attribute of the script element has been deprecated long ago.
Update: this piece of code
<script type="text/javascript" for="window" event="onload">
// <!CDATA[
return window_onload()
// ]]>
</script>
uses an IE-specific way to attach an event handler. Never use it!
Instead, use a DOM level 2 method or just
window.onload = window_onload;
You need to ensure that the DOM is ready before you start to interact with it.
I'd recommend using jQuery and wrapping your DOM-interactive code in the .ready() event hander, like this:
$(document).ready(function(){
init();
});
That way you can be sure that all your elements exist before you start to reference them, as stated in the jQuery API reference:
The handler passed to .ready() is
guaranteed to be executed after the
DOM is ready, so this is usually the
best place to attach all other event
handlers and run other jQuery code.
put your script tags after newsDiv. I think the problem arises because the html hasn't rendered yet.
Make sure that you have java script functions available in your page. Some times you get such errors when no method is accessible.

Categories