When is the 'javascript:' prefix valid syntax? - javascript

I know that you can use a javascript: pseudo protocol for URLs in an <a> tag. However, I've noticed that Firefox and IE will both allow 'javascript:' to precede javascript code within a <script> tag. Is this valid syntax? Does it change the scoping rules?
Examples:
I've seen this many times:
<a onclick="javascript:alert('hello world!');">Hello World!</a>
But is this legal/valid syntax and does it do anything special:
<script type="text/javascript">
javascript:alert('hello world!');
</script>

Outside of the href attribute (where it is a protocol specifier), name: just creates a label (such as one might use with a continue or break).
See: Do you ever need to specify javascript: in an onclick?

You need the javascript: "protocol" when you want to put JavaScript in the href attribute of a link.
<!-- does not work -->
link
<!-- does work -->
link
<!-- also works -->
link
As far as I know (and please, if I'm wrong, someone correct me) there is no difference in scope, but there is a very important difference about this.
<!-- does not work -->
link
<!-- alerts "undefined" -->
link
<!-- works as expected, alerts "<url>#" -->
link

One thing to consider, our testers would always ding us if we did something like
<a href='javascript:openwindowmethod("url");'> stuff </a>
Rather than
<a href='url' onclick='return openwindowmethod(this.href);'> stuff </a>
The first method would only work if you click on it but not if you shift or alt clicked on it, or right clicked and went to open in a new window.
The second method would support all of that, as well as the ability to function the way it intended if the user just plain clicked the link.

The javascript: syntax can be used anywhere in a URL and executes the following string as a script. It is part of the HTML spec and AFAIK is supported by all current major browsers.

Related

Include html in another html file for Adsence

I'm trying to include my Adsense code from a file called sda.html located in the home folder of the server.
I'm using this code to include it:
<div w3-include-html="../../sda.html" class="section_title text-center"></div>
from this source: https://www.w3schools.com/howto/howto_html_include.asp
but idk I feel there's something wrong.
btw my site is only HTML and js, so if there is any other better option I'll be glad to hear it.
I also checked this one down:
<!--#include virtual="/menu.shtml" -->
but I didn't use it, since I have no clue how my next server will operated. so I skip it.
and this one here:
<object data="../../sda.html"></object>
I prefer this one, but I have no control of the look of it, I couldn't center or anything
the smaller the code the better it is.
Does sda.html contains only adsense code or whole part of the page?
The includeHTML function from w3school is not very good. I suspect the issue you are having is that that function uses innerHTML to set content and innerHTML doesn't execute <script> tags with content: check "Security considerations" on MDN page.
To workaround this you can do the following: remove <script> tags from sda.html and then, once you imported HTML run window.adsbygoogle.push({}) for each new ad unit. Example:
Add adsbygoogle.js tag in of your page:
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
Insert ad into a div with id div-with-ad.
const divWithAd = document.querySelector('#div-with-ad');
divWithAd.innerHTML = `
<ins class="adsbygoogle"
style="display:block; text-align:center;"
data-ad-format="fluid"
data-ad-layout="in-article"
data-ad-client="ca-pub-0123456789101112"
data-ad-slot="9876543210"></ins>
`;
adsbygoog.push({});

how get a value inside ui:repeat for javascript [duplicate]

I would like to know how I can pass JSF managed bean properties to a JavaScript function.
Something like this:
<script>
function actualizaMenu(key){
#{linkedMenu.setKey(key)}
}
</script>
<ul>
<ui:repeat value="#{moduleList.modulos}" var="entity">
<li>
<a onclick="actualizaMenu(#{entity.key})">#{entity.nombre}</a>
</li>
</ui:repeat>
</ul>
This is not exactly "passing" of JSF variables. This is just printing JSF variables as if they are JavaScript variables/values. You know, JSF and JS do not run in sync at all. JSF runs in webserver and produces HTML/CSS/JS code which in turn runs in webbrowser once arrived over there.
Your concrete problem is most likely caused because you wrote JSF code in such way that it generates invalid JS syntax. An easy way to verify that is by just checking the JSF-generated HTML output which you can find by rightclick, View Source in browser, and by checking if you don't see any syntax error reports in the JS console in browser which you can find by pressing F12 in Chrome/IE9+/Firefox23+.
Imagine that #{entity.key} here
<a onclick="actualizaMenu(#{entity.key})">#{entity.nombre}</a>
prints a Java string variable like "foo", then the generated HTML would look like
<a onclick="actualizaMenu(foo)">some name</a>
But hey, look, that represents a JavaScript variable named foo, not a JS string value! So if you actually want to ultimately end up as
<a onclick="actualizaMenu('foo')">some name</a>
then you should instruct JSF to generate exactly that HTML:
<a onclick="actualizaMenu('#{entity.key}')">#{entity.nombre}</a>
Beware of special characters in the JSF variable though. You can use OmniFaces of:escapeJS() function for that.
Unrelated to the concrete problem, the concrete implementation of actualizaMenu() makes no sense. You seem to be attempting to set a bean property. You should not use JS for that, but a <h:commandLink> instead.
<h:commandLink value="#{entity.nombre}" action="#{linkedMenu.setKey(entity.key)}" />
Nest if necessary a <f:ajax> to make it asynchronous.
I would recommend using event binding with jQuery and the data attribute on elements to get the same result (assuming you use jQuery):
<script>
function actualizaMenu(key){
/* Logic here ... */
}
$(document).ready(function(){
$('.menuItem').click(function(){
var key = $(this).data('key');
actualizaMenu(key);
);
});
</script>
...
<ul>
<ui:repeat value="#{moduleList.modulos}" var="entity">
<li>
<a data-key="#{entity.key}" class="menuItem">#{entity.nombre}</a>
</li>
</ui:repeat>
</ul>
And, as pointed out elsewhere, unless #{linkedMenu.setKey(key)} actually returns a piece of javascript (which seams unlikely and would probably be really bad even if it did) you need to fix the function as well.
I know this question is old, but to those who are still looking there's an alternative.
If you are using primefaces just try this out.
Request Context

HTML/JS: Confused about method to create an image button

I need to create a simple button made only of an image, and which will open a JQuery Dialog when the user clicks on it.
I am doing some reading and notice many solutions: <button>, <image> with a <a>, using CSS to modify a button background, etc...
This is confusing, what is the proper way to implement my image button?
Thanks.
P.S.: The button/image should be focussable. An operational JSFiddle example is welcome.
The proper way largely depends on what the button will do if JavaScript is not available.
If you are going to submit a form then:
<button> <img src="..." alt="..."> </button>
If you are going to go to a URL then:
<img src="..." alt="...">
If you are going to do absolutely nothing (generally not a good idea, you should follow the principles of Progressive Enhancement and Unobtrusive JavaScript, but acceptable if you only generate the button with JavaScript in the first place and the loss to the user is convenience rather then essential functionality):
<button type="button"> <img src="..." alt="..."> </button>
You then bind the JavaScript to either the form's submit event, or the button/anchor's click event and prevent the default behaviour so the form won't be submitted / the link won't be followed if the JavaScript executes successfully.
Create a button and put background-image for it.
Checkout the fiddle.
http://jsfiddle.net/siyakunde/Y38nz/
I found the solution after many struggles: http://jsfiddle.net/YRY8M/3/.
<html>
<head></head>
<body>
<input type="image" tabindex="0" onclick="doSomething()" src="http://upload.wikimedia.org/wikipedia/commons/thumb/0/0c/White_and_yellow_flower.JPG/320px-White_and_yellow_flower.JPG"
/>
<br />
<button tabindex="1">I am focussable too !!!</button>
</body>
</html>
And some javascript:
function doSomething() {
alert('Hello!');
}
It depends on what you want to do in every case. There is no guideline that says "you should do it like this", but there are situations that some cases are more suitable than others.
For example according to this review, IE versions of 8 and below have some buggy behaviour regarding <button> tag when trying to use it as a submit button.
Ηowever the <button> has some new attributes added in HTML5 which you can see here , ammong them is autofocus and other useful that will be supported by most modern major browsers.
In your case that you want to maintain the "focus" (i assume with tabbing support), if you use a single <image> as a button (with or without <a>), you will have to add some JS code to make the image focusable when the appropriate tab is pressed. So you will have to write a bit more code to do the same thing.
There is one more solution which might be suitable for you, since you do not need to submit the form to server side. Using the <input type="image" type and defining the src attribute inside it, will be focusable and not require neither any JS code to run nor any difficult CSS. You can find more about it's syntax here
So, it ends up to you to decide which one of all them to use.
I would use the one that i find more flexible, easier for me to code, easily reusable and is supported by most of my target browsers.
Use jQuery as you own it...
<html>
<head>
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<style type="text/css">
#theBtn{
margin: 20% auto 0;
background: url('http://upload.wikimedia.org/wikipedia/commons/thumb/0/0c/White_and_yellow_flower.JPG/320px-White_and_yellow_flower.JPG');
width: 100px;
height: 50px;
}
</style>
</head>
<body>
<div id="theBtn"></div>
<script type="text/javascript">
$(document).ready(function(){
$("#theBtn").click(function(){
if(confirm('Are you sure?')){
$("#theBtn").fadeOut('slow');
}
});
});
</script>
</body>
</html>
Inside a <button> tag , put your image, and attach an click event to <button> to open the dialog on click.
JSFiddle
First thing, There is either an image or a button. But not both.
I would say, create an image and place your code in the onclick() function of that image.
var img= $("#my-image-id");
image.click(function() {
// your code here
}
As I know You can't change the look of the Safari buttons thats why I suggest to use a for the solution. Here is my simple code: http://jsfiddle.net/djgBK/1/
The basis is:
Take an a element put the link content to the left,
Then replace it with image that is actualy it's background. Becouse it's a element user can select it usin only TAB button.
What's more using an a elemet will let You to put title which will be displayed after hovering/entering over the button.

Underscore template in HTML generating mysterious 404 errors

Okay, I have this underscore template (simplified version), rendered from _template.html.erb, in my Rails app, somewhere on the page:
<script type="text/html" id="mytemplate">
<div class="foo">
<img src="{{= my_variable }}" />
</div>
</script>
Then I render it like this, elsewhere, when required:
// change it to mustache-style because of defaults clashing with erb
_.templateSettings = {
interpolate: /\{\{\=(.+?)\}\}/g,
evaluate: /\{\{(.+?)\}\}/g
};
options = {
my_variable: '/foo/bar/baz.img'
}
compiled = _.template($("#mytemplate").html());
$(compiled(options)).appendTo("#wherever");
This, in theory should work just fine and it does, except errors like this started popping up in server logs and elsewhere, browsers 404-ing on URLs like: http://example.com/{{=%20my_variable%20}}, or http://example.com/foo/{{=%20my_variable%20}}.
Now, my hunch is that it has something to do with the fact that it's an img tag and somehow the browser tries to GET it from the page, even though it's wrapped in script tags, but I have no idea why on earth. This is one of the recommended methods by many people for embedding underscore templates into HTML. And I can't attribute it to older browsers and/or robots either because server logs show these are real people using the latest Chrome etc.
Edit: after a bit more investigating, 1. it only happens to a few people (unique IPs) 2. all of them are using the latest version of Chrome. So maybe it's an extension gone haywire?
Any ideas?
You must change the type="text/html" to something non-existent like type="x-template" (or anything really)
This normally works if the cache is cleared and all.
If nothing really does it, then you could use external templates (files that you load). But if you want to keep them inline, then escape the problematics chars (with internal JS char encoding). This will be parsed the same by JS, but won't get caught by HTML parser.
You can use this tool: http://mothereff.in/js-escapes (uncheck the "only escape non-ASCII and unprintable ASCII characters" box)
That's what it could looks like:
<script type="text/html" id="mytemplate">
<div class="foo">
\x3Cimg src="{{= my_variable }}" />
</div>
</script>

A random '#.XXXXXXXXXXX' string is added to my URL when I use the AddThis code?

I have added "AddThis" to my website and this is the code I have used :
<!-- AddThis Button BEGIN -->
<a class="addthis_button_facebook_like" addthis:url="http://facebook.com/MySpills" fb:like:layout="button_count"></a>
<a class="addthis_button_tweet"></a>
<a class="addthis_button_google_plusone" g:plusone:size="medium"></a>
<script type="text/javascript">var addthis_config = {"data_track_addressbar":true};</script>
<script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#pubid=ra-4fabf4922f71c398"></script>
<!-- AddThis Button END -->
Now for some reason, every time I go to a page this happens to the URL:
http://domain/page#.T7FTDJ8ti28
The #.T7FTDJ8ti28 changes every time I refresh the page, and I am concerned that this might confuse Google or other search engines. It also just doesn't look good to have it in the URL, so how can I get rid of it?
That is commonly calling: a HASH and it serves to several things.
In AddThis context, it serves to track links in a way so they know what is a direct link and a shared link.
All is explained in their analytics article.
This will not have any impact on Search Engine Optimization (SEO) as the rule is to track the regular link part and not the hashed part.
If, by the way, you want to know more on how the hash part of a web address is used for, the link below is a good start point article to read.
Are We Breaking the Web With a Hash and a Bang?
Change
var addthis_config = {"data_track_addressbar":true};
To
var addthis_config = {"data_track_addressbar":false};

Categories