How to embed JavaScript in PHP within div (in an include file)? - javascript

I'm trying to get an image to display in a div depending on the URL of the page. This div is in an include file that gets used for all pages of the website. What I want is if it's the homepage (with or without index.php), is for the div to show the image. What I've pieced together so far is:
<script type="text/javascript">
var d = location.href
if (d="website.com" || "website.com/index.php")
{
<img src="/images/DSLogo2.jpg" />;
}
</script>
I'm not sure if this is correct, or even the best way to go about it. Any help is very greatly appreciated, as I am still learning more and more each day.

Try:
<script type="text/javascript">
var d = window.location.href
if (d="website.com" || "website.com/index.php")
{
document.write('<img src="/images/DSLogo2.jpg" />');
}
</script>

Do not confuse = and == operator. The correct way how to code the condition is
if (d=="website.com" || d=="website.com/index.php")
Javascript is not a preprocessor, you can't usi it to create the code like in PHP. If you want to add element, you have to work with DOM:
<div id="target"></div>
<script>
var d = location.href;
var target = document.getElementById("target");
if (d=="website.com" || d=="website.com/index.php") {
target.innerHTML = '<img src="/images/DSLogo2.jpg"/>';
}
</script>

JavaScript doesn't work that way. You could use document.write with logic like that but something like this would be better:
if (your logic here) {
var image = document.getElementById('my_image');
image.src = 'some_image.jpg';
}
Notice that assumes you'll have a unique id on your image element. You'll want to put this logic in the document ready event or window on load.

Related

My code executed only in console but not working in .js file

I have tried the following code to replace text character to the img tag inside div message.
However the code is working fine while i do in console. But when I try the same in my sticker.js is not working. Can anyone tell me the reason?
The idea to make sticker box for chat app codded with Javascript and jQuery.
User 1 will send :sticker1: to public room and replaced with img src inside the #div
Now I'm trying document to call the script when div is showing but still not working.
$(document).ready(function() is not working
And $(function() is not working either.
My chat app using template folder /template/*.php and web-cache folder to load the design. I am searching every where to find some solution but no luck.
I need help please
$("#chat-sticker-container").ready(function stickers() {
var emoCodes = [
':sticker1:',
];
var $this = $("body");
emoCodes.forEach(function(code) {
var image = '<img src="https://sevendays.co.in/wp-content/uploads/2019/02/' + code.replace(/:/g, "") + '.jpg">';
$this.find('p.chat-sticker').html(function(index, html) {
return html.replace(new RegExp(code, "g"), image);
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="js/sticker.js"></script>
<dive id="chat-sticker-container">
<p id="chat-sticker" class="chat-sticker">:sticker1:</p>
</dive>
Make sure your JS is executing AFTER the html is in the DOM, this includes putting your script at the end of your body tag.
Since the script is called before the html is defined its essentially working with nothing, putting the after the html should fix the issues.
By looking at your JSFiddle example I think you need to use the MutationObserver API. This way you can check if an element, or the children of an element have been changed, added or removed.
I'm not able to figure out what the container is where the chat divs are added to the page, so I can only instruct you. But based on your fiddle I'm selecting the chat-main-scroll-chatroom div.
// List of emoCodes
var emoCodes = [
':sticker1:',
];
// Select chat container. Change if necessary.
var chatContainer = document.getElementById('chat-main-scroll-chatroom');
// Create a new observer.
var observer = new MutationObserver(function(entries) {
// Check for emocodes whenever something has changed.
emoCodes.forEach(function(code) {
var image = '<img src="https://sevendays.co.in/wp-content/uploads/2019/02/' + code.replace(/:/g, "") + '.jpg">';
$('p.chat-sticker').html(function(index, html) {
return html.replace(new RegExp(code, "g"), image);
});
});
});
// Check if children are changed
var options = { childList: true }
// Observer the chat container and check if itself or children are changing.
observer.observe(chatContainer, options);
So I really hope that this will help you out. In the best case scenario you would be able to filter the text that has been sent before the message is sent. If the API of your chat app provides such controls, then please use them.
Best of luck!

How to load javascript src file into new tab [duplicate]

I'm having problems getting this to work. I first tried setting my script tags as strings and then using jquery replaceWith() to add them to the document after page load:
var a = '<script type="text/javascript">some script here</script>';
$('#someelement').replaceWith(a);
But I got string literal errors on that var. I then tried encoding the string like:
var a = '&left;script type="text/javascript">some script here<\/script>';
but sending that to replaceWith() outputs just that string to the browser.
Can someone please let me know how you would go about dynamically adding a <script> tag into the browser after page load, ideally via jQuery?
You can put the script into a separate file, then use $.getScript to load and run it.
Example:
$.getScript("test.js", function(){
alert("Running test.js");
});
Try the following:
<script type="text/javascript">
// Use any event to append the code
$(document).ready(function()
{
var s = document.createElement("script");
s.type = "text/javascript";
s.src = "http://scriptlocation/das.js";
// Use any selector
$("head").append(s);
});
http://api.jquery.com/append
Here's the correct way to do it with modern (2014) JQuery:
$(function () {
$('<script>')
.attr('type', 'text/javascript')
.text('some script here')
.appendTo('head');
})
or if you really want to replace a div you could do:
$(function () {
$('<script>')
.attr('type', 'text/javascript')
.text('some script here')
.replaceAll('#someelement');
});
A simpler way is:
$('head').append('<script type="text/javascript" src="your.js"></script>');
You can also use this form to load css.
This answer is technically similar or equal to what jcoffland answered.
I just added a query to detect if a script is already present or not.
I need this because I work in an intranet website with a couple of modules, of which some are sharing scripts or bring their own, but these scripts do not need to be loaded everytime again. I am using this snippet since more than a year in production environment, it works like a charme. Commenting to myself: Yes I know, it would be more correct to ask if a function exists... :-)
if (!$('head > script[src="js/jquery.searchable.min.js"]').length) {
$('head').append($('<script />').attr('src','js/jquery.searchable.min.js'));
}
Here is a much clearer way — no need for jQuery — which adds a script as the last child of <body>:
document.body.innerHTML +='<script src="mycdn.js"><\/script>'
But if you want to add and load scripts use Rocket Hazmat's method.
Example:
var a = '<script type="text/javascript">some script here</script>';
$('#someelement').replaceWith(a);
It should work. I tried it; same outcome. But when I used this:
var length = 1;
var html = "";
for (var i = 0; i < length; i++) {
html += '<div id="codeSnippet"></div>';
html += '<script type="text/javascript">';
html += 'your script here';
html += '</script>';
}
$('#someElement').replaceWith(a);
This worked for me.
Edit: I forgot the #someelement (btw I might want to use #someElement because of conventions)
The most important thing here is the += so the html is added and not replaced.
Leave a comment if it didn't work. I'd like to help you out!
There is one workaround that sounds more like a hack and I agree it's not the most elegant way of doing it, but works 100%:
Say your AJAX response is something like
<b>some html</b>
<script>alert("and some javscript")
Note that I've skipped the closing tag on purpose. Then in the script that loads the above, do the following:
$.ajax({
url: "path/to/return/the-above-js+html.php",
success: function(newhtml){
newhtml += "<";
newhtml += "/script>";
$("head").append(newhtml);
}
});
Just don't ask me why :-) This is one of those things I've come to as a result of desperate almost random trials and fails.
I have no complete suggestions on how it works, but interestingly enough, it will NOT work if you append the closing tag in one line.
In times like these, I feel like I've successfully divided by zero.
If you are trying to run some dynamically generated JavaScript, you would be slightly better off by using eval. However, JavaScript is such a dynamic language that you really should not have a need for that.
If the script is static, then Rocket's getScript-suggestion is the way to go.

Inserting variable (grabbed from json) into element

I have a function to grab a video title from a YouTube json callback, which works - however I'm having issues inserting the variable into an element.
Here is the feed I'm grabbing:
<script type="text/javascript" src="http://gdata.youtube.com/feeds/api/videos/2WNrx2jq184?v=2&alt=json-in-script&callback=youtubeFeedCallback"></script>
The javascript function I'm using:
function youtubeFeedCallback(data) {
var info = data.entry.title.$t;
document.write(info);
}
This works fine, but I'd like to insert it into a div with the ID "box".
Usually I would use the following (and add it to the function - and remove the document.write):
var box = document.getElementById('box');
box.innerHTML = info;
I just cannot get this to work though. What would be the correct way to achieve what I'm trying to do? Thanks
http://jsfiddle.net/b3VYT/
Either make sure that the script is below the element or wrap your code in a document.ready callback so that it is not run until after the DOM is loaded.
http://jsfiddle.net/b3VYT/1
You need to make sure that the element that you are using is declared prior to your script executing:
<div id='test'></div>
<script>
function youtubeFeedCallback(data) {
document.getElementById('test').innerHTML = data.entry.title.$t;
}
</script>
Example

change two values with one if statement

I'm just starting to learn javascript, so this is likely a pretty simple question. I've tried searching for an answer, but I think I just don't know enough to be like, 'oh, this looks different but answers my question too.'
What I want to be able to do is to change the background color of a page based on the time of day, and also change an image based on the time of day. I have it working with an if...else if... statement for the background color placed in the head of the page, and a separate if...else if... statement affecting the image in the body.
The head script that changes the bg color looks like:
var d=new Date();
var time=d.getHours();
if (time>=0 && time<=5)
{
document.write ('<body style="background-color: 296688">')
}
else if
...and then the other times follow, each with a different color.
The body script that changes the image looks like:
<img src="" name="sunMoon" id="sunMoon" />
<script type="text/javascript">
var d=new Date();
var time=d.getHours();
var elem = document.getElementById('sunMoon')
if (time>=0 && time<=5)
{
elem.src = 'Images/sunMoon1.png'
}
else if
...and then the other times follow, each with a different src.
Is it possible to change the image AND the bg color using the same if...else if... statement in the head? I tried something like this in the head:
var d=new Date();
var time=d.getHours();
var elem=document.getElementById('sunMoon')
if (time>=0 && time<=5)
{
document.write ('<body style="background-color: 2966B8">');
elem.src="images/sunMoon1.png"
}
else if...
but it didn't work.
I think with the third (nonworking) example, either it's not possible to have a single if... do two things (change the bg color AND the image), or I'm just messing up the image code.
The problem with your third (non-working) bit of code is that you are trying to change the source attribute of an element that doesn't exist when the script is run. Generally speaking the browser parses the page's HTML from top to bottom, when it comes across a block it runs the code then continues on through the HTML. So in the example you have working the JavaScript code that alters the image source comes after the element in the HTML which is why it works. In the broken code you call elem=document.getElementById('sunMoon') in the head section, so no element with ID 'sunMoon' exists yet.
Generally it is best practice to place your scripts at the bottom of the page (just before the closing tag) so that they run after everything else has loaded, and don't block the rendering of the page. If you were to do that you'd need to change the code that alters the background colour as you can't write it directly to the body tag. The best practice solution would be to apply a different CSS class to the body depending on the time of day and then set up style rules for each class in your CSS.
So for example:
<script type="text/javascript">
var body = document.getElementsByTagName('body')[0];
var elem = document.getElementById('sunMoon');
if (time>=0 && time<5)
{
body.className = 'morning';
elem.src = 'Images/sunMoon1.png';
}
else if (time>=5 && time<10)
{
body.className = 'afternoon';
elem.src = 'Images/sunMoon2.png';
}
</script>
Then in your CSS you need rules for .morning, .afternoon etc
Yes you can, you can change the body style like this:
document.body.style.backgroundcolor = color;
Yes you can use
var d=new Date();
var time=d.getHours();
var elem=document.getElementById('sunMoon')
if (time>=0 && time<=5)
{
document.body.style.backgroundImage ="images/sunMoon1.png";
document.body.style.backgroundColor = "#2966B8";
}
use onload event
<html>
<head>
<script>
function onBodyload(e){
var image = document.getElementById('sunMoon');
if(condition){
document.body.style.backgroundcolor = ...
image.src = ...
}else if(condition){
document.body.style.backgroundcolor = ...
image.src = ...
}else if...
}
</script>
</head>
<body onload="onBodyload">
...
...
</body>
</html>

How can we keep OpenX from blocking page load?

We're using OpenX to serve ads on a number of sites. If the OpenX server has problems, however, it blocks page loads on these sites. I'd rather have the sites fail gracefully, i.e. load the pages without the ads and fill them in when they become available.
We're using OpenX's single page call, and we're giving divs explicit size in CSS so they can be laid out without their contents, but still loading the script blocks page load. Are there other best practices for speeding up pages with OpenX?
We load our ads in iframes to avoid the problem you're having. We size div and the iframe the same, with the iframe pointing to a page which just contains the ad snippet (you can pass the zone and other required options as parameters to that page).
cheers
Lee
We lazy-load OpenX's code. Instead of putting the single-page call at the top of the page, we put it at the bottom. After the page has loaded, the call will get the banner data and a custom code will add the correct banners in the correct zones.
The code below requires a proper DOM. If you have jQuery, DOMAssistant, FlowJS, etc, the DOM should be fixed for you.
This code will work with normal banners with images, flash, or HTML content. It may not work in some cases like when using banners from external providers (adform, etc). For that you may need to hack the code a bit.
How to use it?
add your SinglePageCall code towards the end of your HTML code
add this code under the SPC code.
after half a second or so, your OpenX code should be ready, and the code below will put the banners within the specified DIVs.
Oh, yeah, you need to add to your HTML code some DIVs as place holders for your banners. By default I have these banners set with CSS class "hidden" which totally hides the DIVs (with visibility, display, and height). Then, after the banner in a given DIV is successfully loaded, we remove the hidden class and the DIV (and the banner within) become visible.
Use at your own risk! :) Hope it helps
(function(){
if (!document || !document.getElementById || !document.addEventListener || !document.removeClass) {
return; // No proper DOM; give up.
}
var openx_timeout = 1, // limit the time we wait for openx
oZones = new Object(), // list of [div_id] => zoneID
displayBannerAds; // function.
// oZones.<divID> = <zoneID>
// eg: oZones.banner_below_job2 = 100;
// (generated on the server side with PHP)
oZones.banner_top = 23;
oZones.banner_bottom = 34;
displayBannerAds = function(){
if( typeof(OA_output)!='undefined' && OA_output.constructor == Array ){
// OpenX SinglePageCall ready!
if (OA_output.length>0) {
for (var zone_div_id in oZones){
zoneid = oZones[zone_div_id];
if(typeof(OA_output[zoneid])!='undefined' && OA_output[zoneid]!='') {
var flashCode,
oDIV = document.getElementById( zone_div_id );
if (oDIV) {
// if it's a flash banner..
if(OA_output[zoneid].indexOf("ox_swf.write")!=-1)
{
// extract javascript code
var pre_code_wrap = "<script type='text/javascript'><!--// <![CDATA[",
post_code_wrap = "// ]]> -->";
flashCode = OA_output[zoneid].substr(OA_output[zoneid].indexOf(pre_code_wrap)+pre_code_wrap.length);
flashCode = flashCode.substr(0, flashCode.indexOf(post_code_wrap));
// replace destination for the SWFObject
flashCode = flashCode.replace(/ox\_swf\.write\(\'(.*)'\)/, "ox_swf.write('"+ oDIV.id +"')");
// insert SWFObject
if( flashCode.indexOf("ox_swf.write")!=-1 ){
eval(flashCode);
oDIV.removeClass('hidden');
}// else: the code was not as expected; don't show it
}else{
// normal image banner; just set the contents of the DIV
oDIV.innerHTML = OA_output[zoneid];
oDIV.removeClass('hidden');
}
}
}
} // end of loop
}//else: no banners on this page
}else{
// not ready, let's wait a bit
if (openx_timeout>80) {
return; // we waited too long; abort
};
setTimeout( displayBannerAds, 10*openx_timeout );
openx_timeout+=4;
}
};
displayBannerAds();
})();
OpenX has some documentation on how to make their tags load asynchronously:
http://docs.openx.com/ad_server/adtagguide_synchjs_implementing_async.html
I've tested it, and it works well in current Chrome/Firefox.
It takes some manual tweaking of their ad code. Their example of how the ad tags should end up:
<html>
<head></head>
<body>
Some content here.
Ad goes here.
<!-- Preserve space while the rest of the page loads. -->
<div id="placeholderId" style="width:728px;height:90px">
<!-- Fallback mechanism to use if unable to load the script tag. -->
<noscript>
<iframe id="4cb4e94bd5bb6" name="4cb4e94bd5bb6"
src="http://d.example.com/w/1.0/afr?auid=8&target=
_blank&cb=INSERT_RANDOM_NUMBER_HERE"
frameborder="0" scrolling="no" width="728"
height="90">
<a href="http://d.example.com/w/1.0/rc?cs=
4cb4e94bd5bb6&cb=INSERT_RANDOM_NUMBER_HERE"
target="_blank">
<img src="http://d.example.com/w/1.0/ai?auid=8&cs=
4cb4e94bd5bb6&cb=INSERT_RANDOM_NUMBER_HERE"
border="0" alt=""></a></iframe>
</noscript>
</div>
<!--Async ad request with multiple parameters.-->
<script type="text/javascript">
var OX_ads = OX_ads || [];
OX_ads.push({
"slot_id":"placeholderId",
"auid":"8",
"tid":"4",
"tg":"_blank",
"r":"http://redirect.clicks.to.here/landing.html",
"rd":"120",
"rm":"2",
"imp_beacon":"HTML for client-side impression beacon",
"fallback":"HTML for client-side fallback"
});
</script>
<!-- Fetch the Tag Library -->
<script type="text/javascript" src="http://d.example.com/w/1.0/jstag"></script>
Some other content here.
</body>
</html>
Following #Rafa excellent answer, i'm using this code to invoke OpenX banners after the page loads. I'm using jquery as well and had to add a new replace call for the "document.write" that flash banners use, and replacing it with "$('#"+ oDIV.id +"').append" instead. I'm using a custom "my_openx()" call, to replace "OA_show()". My banners area called by the zone_id and are wrapped inside a div, like this:
<div id="openx-4"><script>wm_openx(4);</script></div>
It's working :)
<script type="text/javascript">
$is_mobile = false;
$document_ready = 0;
$(document).ready(function() {
$document_ready = 1;
if( $('#MobileCheck').css('display') == 'inline' ) {
$is_mobile = true;
//alert('is_mobile: '+$is_mobile);
}
});
function wm_openx($id) {
if($is_mobile) return false;
if(!$document_ready) {
setTimeout(function(){ wm_openx($id); },1000);
return false;
}
if(typeof(OA_output[$id])!='undefined' && OA_output[$id]!='') {
var flashCode,
oDIV = document.getElementById('openx-'+$id);
if (oDIV) {
// if it's a flash banner..
if(OA_output[$id].indexOf("ox_swf.write")!=-1) {
// extract javascript code
var pre_code_wrap = "<script type='text/javascript'><!--// <![CDATA[",
post_code_wrap = "// ]]> -->";
flashCode = OA_output[$id].substr(OA_output[$id].indexOf(pre_code_wrap)+pre_code_wrap.length);
flashCode = flashCode.substr(0, flashCode.indexOf(post_code_wrap));
// replace destination for the SWFObject
flashCode = flashCode.replace(/ox\_swf\.write\(\'(.*)'\)/, "ox_swf.write('"+ oDIV.id +"')");
flashCode = flashCode.replace(/document.write/, "$('#"+ oDIV.id +"').append");
// insert SWFObject
if( flashCode.indexOf("ox_swf.write")!=-1 ) {
//alert(flashCode);
eval(flashCode);
//oDIV.removeClass('hidden');
}// else: the code was not as expected; don't show it
}else{
// normal image banner; just set the contents of the DIV
oDIV.innerHTML = OA_output[$id];
//oDIV.removeClass('hidden');
}
}
}
//OA_show($id);
}
</script>
I was looking for this to load advertising from my openX server only when the advertising should be visible. I'm using the iFrame version of openX which is loaded in a div. The answer here put me on my way to solving this problem, but the posted solution is a bit too simple. First of all, when the page is not loaded from the top (in case the user enters the page by clicking 'back') none of the divs are loaded. So you'll need something like this:
$(document).ready(function(){
$(window).scroll(lazyload);
lazyload();
});
also, you'll need to know what defines a visible div. That can be a div that's fully visible or partially visible. If the bottom of the object is greater or equal to the top of the window AND the top of the object is smaller or equal to the bottom of the window it should be visible (or in this case: loaded). Your function lazyload may look like this:
function lazyload(){
var wt = $(window).scrollTop(); //* top of the window
var wb = wt + $(window).height(); //* bottom of the window
$(".ads").each(function(){
var ot = $(this).offset().top; //* top of object (i.e. advertising div)
var ob = ot + $(this).height(); //* bottom of object
if(!$(this).attr("loaded") && wt<=ob && wb >= ot){
$(this).html("here goes the iframe definition");
$(this).attr("loaded",true);
}
});
}
Tested on all major browsers and even on my iPhone, works like a charm!!

Categories

Resources