How do you make an HTML button behave just like a hyperlink? - javascript

How do you make an HTML button behave just like a hyperlink where, if you click on it, it will open a browser window showing a page you want?
I understand this much. I think I will use this
but instead of a link to some javascript code inside the quotes for "onclick" I want to put something simple that will launch a new browser window.

onclick and window.open
<input type="button" onclick="window.open('http://www.example.com','_blank','resizable=yes')" />

In Head:
<script>
openNewWindow = function()
{
window.open(url, "_blank");
};
</script>
In Body:
<input type="button" onclick="openNewWindow()" >
I prefer to define a function named openNewWindow() instead of putting the code in the input tag. This is for organization. I highly recommend you do this if you're planning on having many different buttons for opening different windows.

I think this is the best solution for you.
Try this out
<a href="http://www.stackoverlfow.com" target="_"><input
type="button" value="Click Me"/></a>
Happy Coding!!

You could do something like this:
window.open(url, "window-name", "menubar=no,innerWidth=600,innerHeight=600,toolbar=no,location=no,screenX=400,screenY=40");
Passing a name to the open method causes the browser to open a new window. The third argument defines the looks of the new window.

<input type="button" value="Google"
onclick="window.open('http://www.google.com', '_blank');" />

I'm 7 years late, I realize, but I had a similar issue and thought I comment for those who may follow.
If you're using Bootstrap, you can attach Bootstrap button classnames to anchor tags and make them look just like buttons:
I Look Like A Button
Bootstrap supports basic sizes as well, including btn-sm or btn-lg. Granted, not everyone uses Bootstrap but even then the default styles are free, easy to find, and can be copied into your own stylesheet even if you're using a custom boilerplate layout.

I've seen a lot of conflicting information regarding Content Security Policies. The primary recommendation from Google's developer site, web.dev is found here => https://web.dev/strict-csp/#what-is-a-strict-content-security-policy.
There are several professional level recommendations stating that a CSP should be used. I write HTML sites, right now, but intend to move to Angular and/or React. In the meantime, the recommendation is that a js script be used to get the element id and forward via the script, rather that using a link.
The justification for this is that cross scripting attackers can use the vulnerability of these elements when the "onclick," or related commands, are used. This removes the vulnerability.
I would recommend approaching it from a CSP point of view and following the linked guidelines to make your site compliant with W3 and Google recommendations.

Related

JavaScript libraries + jQuery plugins contradict: how to debug?

I'm not the very best expert, but I can do a decent job good looking and functional websites or web applications. My main tools are PHP5, HTML5, CSS2 y 3, a database (SQLite, MySQL) and JavaScript and jQuery.
I'm not an expert at all in JavaScript. I often find interesting jQuery plugins or tutorials and try to mix them up to do the functionality needed. This time I'm mixing maybe too much plugins and js files from different sources.
In fact, my app do what I want except for certain behaviors. There are no errors, everything looks fine, but the misbehavior persists. So maybe I need to specify a class I don't know about, or one contradicts another one from another plugin and I just can't understand, for example, why a <button type="button">DON'T submit</button> just submits the form.
Anyway, my point is: how can I debug this situation? Is there a generic tool, suggestion, workflow or something to help me understand conflicts or omissions between libraries or plugins? (JavaScript libraries, my own JavaScripts and jQuery plugins)?
Edit
I know about Chrome's debugger and Firebug. But maybe I just don't know how to get the functionality I need. Reading about how to use these tools haven't helped me. For example: I've got a tag which has inherit a class I didn't assigned it to by hand (example: <button type="button" disabled>DON'T submit</button> I didn't write disabled by myself) So some JavaScript file is assigning it, but how can I see WHO did this? Which file? Class? Plugin? Library? Etc? That's another example of what I mean to ask.
It is possible that you're using two libraries that use the $() function. In jQuery, the $() function is just shorthand for jQuery(), so you could try taking your jQuery code and replacing every instance of "$(" with "jQuery(" and see if that helps out. Without know what scripts you're using I can't tell if that will work or not, but this is likely the problem if you have more than one framework (e.g. jQuery) loaded at one time.
Just make sure you don't change any non-jQuery functions from $() to jQuery() or else they'll break.
The default functionality of the <button> tag is the same as <input type="submit">.
http://htmldog.com/reference/htmltags/button/
Yes, there are tools to debug javascript.
Chrome as inbuilt debugger (Press F12 to open it)
But my favourite is firebug (its an addon for firefox, download it from here)
To resolve the conflicting issue, read here
Also, by default <button> submits the form.
If you do not want <button> to submit form, you can use this,
<button type="button" onclick='return false;'>DON'T submit</button>

Multiple windows in one page for bookmarks

I want a single online web page for my bookmarks. The page should include small windows which opens the following pages:
Fizy, Facebook, Guardian.
There should also be a button for adding a new window with an URL text input.
Here's an illustration of how the page should look: http://i54.tinypic.com/2hrkb48.jpg
I've built a version of this at http://bit.ly/heqEd1, but as you may see, it uses iframes under javascript windows, which can not open frame-breaking sites (like fizy.com), or Facebook.
I'll make the research and but I am not sure how to proceed. Any solution will be accepted, like HTML5, XUL, Flex, AJAX or others. A solution with a local installation(like a Firefox extension) is not preferred, but still be ok.
Note: Piro Sakura has built a Firefox extension called split-browser. There's an element of the project called "subbrowser". An AJAX window that can show a subbrowser MAY solve the problem. I know the page will only be available from Firefox, but that is ok. (Again, a solution without an installation is preferred)
Any suggestions? How should I proceed? What should I learn? Is this possible?
Thanks.
I think you should use a Javascript with iFrames to do this. I'm not too sure what you're trying to accomplish with this, but it should be possible. As for which framework you'll use, it's up to you, but there will be a lot of custom code needed to implement this.
You can make multiple draggable windows in FLEX same as you have in you app
Please check sample as Starting point Movable/Draggable window and its demo
also u knows JS-DESKTOP lib with little customization to achieve that one of them are
jsdesk
sonspring-JQuery based
also you can do this using
Hopes that helps

Is it alright to use target="_blank" in HTML5?

I recall reading somewhere that in HTML5 it was no longer okay to use target="_blank" in HTML5, but I can't find it now.
Is it alright to continue to use target="_blank"?
I know it's generally considered a bad idea, but it's by the easiest way to open a new window for something like a PDF, and it also doesn't require you to rely on JavaScript.
It looks like target="_blank" is still alright. It is listed as a browsing context keyword in the latest HTML5 draft.
It is ok to use target="_blank"; This was done away with in XHTML because targeting new windows will always bring up the pop-up alert in most browsers. XHTML will always show an error with the target attribute in a validate.
HTML 5 brought it back because we still use it. It's our friend and we can't let go.
Never let go.
Though the target="_blank" is acceptable in HTML5, I personally try never to use it (even for opening PDFs in a new window).
HTML should define meaning and content. Ask yourself, “would the meaning of the a element change if the target attribute were removed?” If not, the code should not go in the HTML. (Actually I’m surprised the W3C kept it… I guess they really just can’t let go.)
Browser behavior, specifically, interactive behavior with the user, should be implemented with client-side scripting languages like JavaScript. Since you want the browser to behave in a particular way, i.e., opening a new window, you should use JS. But as you mentioned, this behavior requires the browser to rely on JS. (Though if your site degrades gracefully, or enhances progressively, or whatever, then it should still be okay. The users with JS disabled won’t miss much.)
That being said, neither of these is the right answer. Out there somewhere is the opinion that how a link opens should ultimately be decided by the end user. Take this example.
You’re surfing Wikipedia, getting deeper and deeper into a rabbit hole. You come across a link in your reading.
Let’s say you want to skim the linked page real quick before coming back. You might open it in a new tab, and then close it when you’re done (because hitting the ‘back’ button and waiting for page reload takes too long). Or, what if it looks interesting and you want to save it for later? Maybe you should open it in a new background tab instead, and keep reading the current page. Or, maybe you decide you’re done reading this page, so you’ll just follow the link in the current tab.
The point is, you have your own workflow, and you’d like your browser to behave accordingly. You might get pretty frustrated if it made these kinds of decisions for you.
THAT being said, web developers should make it absolutely clear where their links go, what types and/or formats of sources they reference, and what they do. Tooltips can be your friend (unless you're using a tablet or phone; in that case, specify these on the mobile site). We all know how much it sucks to be taken somewhere we weren't expecting or make something happen we didn't mean to.
it's by the easiest way to open a new window for something like a PDF
It's also the easiest way to annoy non-Windows users. PDF open just fine in browsers on other platforms. Opening a new window also messes up the navigation history and complicates matter on smaller platforms like smartphones.
Do NOT open new windows for things like PDF just because older versions of Windows were broken.
Most web developers use target="_blank" only to open links in new tab. If you use target="_blank" only to open links in a new tab, then it is vulnerable to an attacker. When you open a link in a new tab ( target="_blank" ), the page that opens in a new tab can access the initial tab and change its location using the window.opener property.
Javascript code:
window.opener.location.replace(malicious URL)
Prevention:
rel="nofollow noopener noreferrer"
More about the attribute values.
While target is still acceptable in HTML5 it is not preferred. To link to a PDF file use the download attribute instead of the target attribute.
Here is an example:
<a href="files/invoice.pdf" download>Invoice</a>
If the original file name is coded for unique file storage you can specify a user-friendly download name by assigning a value to the download attribute:
Invoice
Keep in mind that while most modern browsers support this feature some may not. See caniuse.com for more info.
It sure is!
http://www.w3.org/TR/2010/WD-html5-20100624/text-level-semantics.html#the-a-element
I think target attribute is deprecated for the <link> element, not <a>, that's probably why you heard it's not supposed to be used anymore.
You can do it in the following way with jquery, this will open it in a new window:
<input type="button" id="idboton" value="google" name="boton" />
<script type="text/javascript">
$('#idboton').click(function(){
window.open('https://www.google.com.co');
});
</script>

What is the proper use of the anchor tag?

I've read how the anchor tag is holy, it should not be used with javascript:
Popup
that it should ONLY be used for a link to another page:
Take me over there
So what is the proper use of the anchor tag with javascript? Should I be using:
Energize!
or some other variant? I'm somewhat confused by different views on the subject. Also is it only SEO that I should be worried about if making the href a javascript piece? Or is it more of a proper web standards compliance deal?
Thoughts? Hopefully I'm not the only one confused.
You are not alone Jakub; even the biggest WWW companies use different approaches.
However based on experiences since Netscape days I wouldn't use :
Popup
which can make some troubles on some browsers, like opening an empty page or breaking the event order on the current page.
However;
Energize!
or;
Link
don't make a serious trouble and are ok to use. Note that the prior one may reset the scroll to the top.
You should use meaningful link targets and unobtrusive javascript wherever possible, but this is not always possible in real life examples. It's not a defined standard, but a method highly agreed by most of the web developers.
When it comes to standards, there is one related with this situation:
You should consider using a 'button' for inputs which doesn't really send the visitor to a page, but does an operation. This is also important for SEO.
As #Sime says (and it should be an answer really), it is considered "bad practise" to now directly reference javascript in any HTML object. So in these cases you attach the event using something like jQuery using the concepts laid out in "unobtrusive javascript".
As you mention another consideration is SEO and accessibility. If SEO is important to your site, make sure that the site is fully navigable using just standard links. Again you can manage this using "unobtrusive javascript", etc.
I've always gone with using an anchor as normal (i.e. specify either an alternate url that is another location where the user could perform what's being done through javascript, or use javascript:void() / #) then use the onclick event for anything you want executed.
You could also use a <span> if you're that worried about conformance, just would need to perhaps style it (change cursor, perhaps color as well) to make it visually obvious you're making it an action.
I think Facebook is the best-case example. Almost all of their links are javascript tied in, but they also have a "backup" page for those that either have disallowed javascript or don't have it (the later, in this day and age, being far less common). Take a look at a module that reacts like you'd like yours to and see how they've done it. They also invested a bunch of work in best-practices that you can benefit from.
If anything, you should bind your anchor links to javascript methods only by using unobtrusive javascript like Paul mentioned.
This means, using separation of concerns and leaving your markup being just that, html markup:
<a id="Jolter">Energize!</a>
and later
<script type="text/javascript">
$(document).ready(function(){
$("#Jolter").click(function(){
// doStuffHere ...
});
});
</script>

What's the purpose (if any) of "javascript:" in event handler tags?

I've been making a concerted effort to improve my javascript skills lately by reading as much javascript code as I can. In doing this I've sometimes seen the javascript: prefix appended to the front of event handler attributes in HTML element tags. What's the purpose of this prefix? Basically, is there any appreciable difference between:
onchange="javascript: myFunction(this)"
and
onchange="myFunction(this)"
?
Probably nothing in your example. My understanding is that javascript: is for anchor tags (in place of an actual href). You'd use it so that your script can execute when the user clicks the link, but without initiating a navigation back to the page (which a blank href coupled with an onclick will do).
For example:
Blah
Rather than:
Blah
It should not be used in event handlers (though most browsers work defensively, and will not punish you). I would also argue that it should not be used in the href attribute of an anchor. If a browser supports javascript, it will use the properly defined event handler. If a browser does not, a javascript: link will appear broken. IMO, it is better to point them to a page explaining that they need to enable javascript to use that functionality, or better yet a non-javascript required version of the functionality. So, something like:
Ajax me
Edit: Thought of a good reason to use javascript:. Bookmarklets. For instance, this one sends you to google reader to view the rss feeds for a page:
var b=document.body;
if(b&&!document.xmlVersion){
void(z=document.createElement('script'));
void(z.src='http://www.google.com/reader/ui/subscribe-bookmarklet.js');
void(b.appendChild(z));
}else{
location='http://www.google.com/reader/view/feed/'+encodeURIComponent(location.href)
}
To have a user easily add this Bookmarklet, you would format it like so:
Drag this to your bookmarks, or right click and bookmark it!
It should only be used in the href tag.
That's ridiculous.
The accepted way is this:
Blah
But to answer the OP, there is generally no reason to use javascript: anymore. In fact, you should attach the javascript event from your script, and not inline in the markup. But, that's a purist thing I think :-D
The origins of javascript: in an event handler is actually just an IE specific thing so that you can specify the language in addition to the handler. This is because vbscript is also a supported client side scripting language in IE. Here's an example of "vbscript:".
In other browsers (as has been said by Shadow2531) javascript: is just a label and is basically ignored.
href="javascript:..." can be used in links to execute javascript code as DannySmurf points out.
javascript: in JS code (like in an onclick attribute) is just a label for use with continue/goto label statements that may or may not be supported by the browser (probably not anywhere). It could be zipzambam: instead. Even if the label can't be used, browsers still accept it so it doesn't cause an error.
This means that if someone's throwing a useless label in an onclick attribute, they probably don't know what they're doing and are just copying and pasting or doing it out of habit from doing the below.
javascript: in the href attribute signifies a Javascript URI.
Example:
javascript:(function()%7Balert(%22test%22)%3B%7D)()%3B
I am no authority in JavaScript, and perhaps more of a dunce than the asker, but AFAIK, the difference is that the javascript: prefix is preferred/required in URI-contexts, where the argument may be as well a traditional HTTP URL as a JavaScript trigger.
So, my intuitive answer would be that, since onChange expects JavaScript, the javascript: prefix is redundant (if not downright erroneous). You can, however, write javascript:myFunction(this) in your address bar, and that function is run. Without the javascript:, your browser would try to interpret myFunction(this) as a URL and tries to fetch the DNS info, browse to that server, etc...
#mercutio
That's ridiculous.
No, it's not ridiculous, javascript: is a pseudo protocol that can indeed only be used as the subject of a link, so he's quite right. Your suggestion is indeed better, but the best way of all is to use unobtrusive javascript techniques to iterate over HTML elements and add behaviour programmatically, as used in libraries like jQuery.
Basically, is there any appreciable difference between: onchange="javascript: myFunction(this)" and onchange="myFunction(this)" ?
Assuming you meant href="javascript: myFunction(this)", yes there is, especially when loading content using the javascript. Using the javascript: pseudo protocol makes the content inaccessible to some humans and all search engines, whereas using a real href and then changing the behaviour of the link using javascript makes the content accessible if javascript is turned off or not available in the particular client.
Flubba:
Use of javascript: in HREF breaks "Open in New Window" and "Open in New Tab" in a Firefox and other browsers.
It isn't "wrong", but if you want to make your site hard to navigate...
I don't know if the javascript: prefix means anything within the onevent attributes but I know they are annoying in anchor tags when trying to open the link in a new tab. The href should be used as a fall back and never to attach javascript to links.

Categories