Disable wavy yellow underline in vs code for HTML - html

How do I ignore this error. I have used the id attribute for some tags in order to reference them by id in javascript, but it shows this error:
CSS id selector '...' not found.
Please tell me how to ignore or disable this error.

maybe your css is not formatted properly.
try:
<style>
#phone {
your css here;
}
</style>
You need to make sure you mark the code with # to show that it's an id and not a class or something else.

Update: First section of answer no longer valid as of the lastest updates since original post which removed the css.validation option. see
If you are using the HTML CSS Support extension by ecmel, you can go to .vscode/settings.json and add
"css.validation": {
"id": false,
"class": false
}
This will turn off css validation for class name and id.
More information on this at the Visual Studio MarketPlace for this extension under Selector Validation here or the Github repository readme Selector Validation Section
Note:
1) Also don't forget to add a comma after the setting that comes before (as JSON format is comma separated).
Example:
{
"java.codeGeneration.generateComments": true,
"css.styleSheets": [
// (1)
"https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css",
"src/main/resources/static/css/styles.css"
],
"css.validation": {
"id": false,
"class": true
}
}
Sometimes you need to restart / close and reopen vscode after saving changed to the file for them take effect.
There is a way to configure styleSheets. This next bit is taken from their documentation see Additional Styles Section:
Additional Style Sheets
If it is not possible to specify local or remote styles in HTML or via
template inheritance, they can be specified in VS Code settings per
workspace folder in .vscode/settings.json and will suggest for all
HTML files within that workspace folder:
.vscode/settings.json
"css.styleSheets": [
// (1)
"https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css",
// (2)
"/site.css",
// (3)
"site.css",
// (4)
"./site.css"
]

Related

Next.js build fails using <img> tag [duplicate]

This question already has answers here:
Error: Do not use <img>. Use Image from 'next/image' instead. - Next.js using html tag <img /> ( with styled components )
(3 answers)
Closed 11 months ago.
I recently started making websites with Next.js, and I have been using a mix of Image and img for various use cases.
I know that Image is built-in to Next.js and is the better choice, but there are scenarios where I do not know the size or the ratio of the images I am loading, and thus the img seems to better suit.
During my recent project, this is the first time my npm run build command is failing with:
1:7 Error: Do not use <img>. Use Image from 'next/image' instead. See https://nextjs.org/docs/messages/no-img-element.
My other Next.js projects do not fail this way, and use the same next.config.js. Does anyone know why this is happening?
This is due to the new Next.js release, which has integrated ESLint with its own set of rules to enforce that <Image> should always be used. Your other projects don't fail because probably you are not using Next.js v11, or they may have their own ESLint config, where you haven't extended next. Ref.: nextjs.org/docs/basic-features/eslint
You can ignore linting during build by this:
// next.config.js
module.exports = {
eslint: { ignoreDuringBuilds: true },
// your other settings here ...
}
If you want to specifically disable the rule for a file or just a line do this: (can be done in two clicks if using ESLint extension in VSCode)
{/* eslint-disable-next-line #next/next/no-img-element */}
<img ... //>
// for whole file, add this to top:
/* eslint-disable #next/next/no-img-element */
// for a section:
/* eslint-disable #next/next/no-img-element */
// your code here...
/* eslint-enable #next/next/no-img-element */
You can also disable the rule using .eslintrc:
{
"extends": "next",
"rules": {
"#next/next/no-img-element": "off",
}
}
You can also ignore (all rules for) a complete file using eslintignore or ignorePatterns. Please refer: eslint.org/docs/user-guide/configuring/ignoring-code

purgecss can't recognize conditional classes

So I'm using TailwindCSS for a WP theme I'm developing.
I ran into an issue in creating the production grade theme files because, from how I understand the problem, purgecss can't recognize conditional classes used on template parts. For example, let's say I created a template part called "business-card.php" where I pass it a variable type (using set_query_var / get_query_var):
page-about.php
set_query_var('type', 'A');
get_template_part('template-parts/content/business', 'card');
set_query_var('type', 'B');
get_template_part('template-parts/content/business', 'card');
businesss-card.php
$type = get_query_var('type')
<div class="<?php echo type == 'A' ? 'text-color-A' : 'text-color-B' ?>">
--- insert some content here ---
</div>
So there will be two divs, one will have a text-color-A class, the other will have a text-color-B, both were created using a config file(rather than included in the base tailwind theme). This is fine in development -- since tailwind does actually create the utility color classes from the config file. But for some reason, when it's in production (i.e. purged & minified), it doesn't have those utility classes -- which were only used in the template part as conditional classes (and not in any other file).
PurgeCSS is intentionally very naive in the way it looks for classes in your HTML. It doesn't try to parse your HTML and look for class attributes or dynamically execute your JavaScript — it simply looks for any strings in the entire file that match this regular expression:
/[^<>"'`\s]*[^<>"'`\s:]/g
That means that it is important to avoid dynamically creating class strings in your templates with string concatenation, otherwise PurgeCSS won't know to preserve those classes.
So do not use string concatenation to create class names:
<div :class="text-{{ error ? 'red' : 'green' }}-600"></div>
Instead, dynamically select a complete class name:
<div :class="{{ error ? 'text-red-600' : 'text-green-600' }}"></div>
As long as a class name appears in your template in its entirety, PurgeCSS will not remove it.
See the docs for more details:
Writing purgeable HTML
If you are using Tailwind 2.0+ you can configure whitelisted classes that will be ignored by purge CSS directly inside of your tailwind.config.js file.
An example of my own code where I whitelist the class text-ingido-400 can be seen below
// tailwind.config.js
module.exports = {
purge: {
content: ['./src/**/*.{js,jsx,ts,tsx}', './public/index.html'],
options: {
safelist: ['text-indigo-400']
}
} ,
darkMode: false, // or 'media' or 'class'
theme: {
extend: {},
},
variants: {
extend: {},
},
plugins: [],
}
For more information you can check out the relevant documentation located at:
https://tailwindcss.com/docs/optimizing-for-production
You can use the PurgeCSS whitelist option to add those classes.
const purgecss = new Purgecss({
//... Your config
whitelist: ['text-color-A', 'text-color-B', 'etc']
})
Or the whitelistPatterns (Regex match)
whitelistPatterns: [/^text-color/], // All classes starting with text-color
You can find more information here
If you define your class names in a variable above where you want to use them it works akin to safe listing them in Tailwind or whitelisting them in PurgeCSS, is potentially easier to maintain, and works good in a pinch if you have a small number of possbile dynamic class names.
var classes =`grid-cols-1 grid-cols-2 grid-cols-3 grid-cols-4`
return (
<div className={`grid grid-cols-${items['grid-cols']}`}>
</div>
)
For some tailwindcss class, you can use inline style instead.
Inline style allow you to use dynamic value, like <div style="padding-left:{indent}rem">.
I think it works in php also. More details can be found here

Airbnb, ESLint, Prettier conflict over Switch and Case indentation

I am setting up my React Redux project to use ESLint with Airbnb configs and Prettier. I've been modifying certain things to how I want them, but now I've run into a problem with indentations on switch & case statements that I can't seem to fix.
I am editing my project in VSCode. I click on the errors and fix with ESLint, reducing the indent by 4 spaces, but then more errors show up from Prettier, asking to re-indent everything by another 4 spaces.
I want to change the current indentation width. I want it set to 4 spaces when I use tabs. It's not a must, but if it is possible, I would prefer that the case keywords in switch blocks to be indented.
List of packages that pertain to my ESLint configuration:
prettier
eslint
eslint-config-airbnb
eslint-plugin-import
eslint-plugin-jsx-a11y
eslint-plugin-react
eslint-import-resolver-webpack
eslint-config-prettier
eslint-plugin-prettier
Relevant portion of my .eslintrc.json
"extends": ["airbnb", "prettier", "prettier/react"],
"plugins": ["react", "prettier"],
"rules": {
"react/jsx-filename-extension": [
1,
{
"extensions": [".js", "jsx"]
}
],
"prettier/prettier": "error",
"indent": ["error", 4, { "SwitchCase": 1 }],
"react/jsx-indent": ["error", 4],
"react/jsx-indent-props": ["error", 4],
"class-methods-use-this": 0,
"no-else-return": 0,
"no-plusplus": [2, { "allowForLoopAfterthoughts": true }],
"no-param-reassign": 0
}
My .prettierrc config-file:
The setting below is necessary for Prettier to format indentations harmoniously with the rest of the development environments configurations while using ESLint.
"prettier": {
"tabWidth": 4
}
Here is the script I am formatting:
It is a hangman game.
switch (action.type) {
case GUESS_LETTER:
return Object.assign(
{},
state,
state.guessWord.includes(action.guessLetter)
? addCorrectGuess(
state.rightLetters.slice(), // <-- error here!
action.guessLetter, // <-- error here!
state.guessWord // <-- error here!
) // <-- error here!
: addWrongGuess(
state.wrongLetters.slice(), // <-- error here!
action.guessLetter // <-- error here!
) // <-- error here!
);
}
My first attempt to get this working was to add { "SwitchCase": 1 } to the ESLint config file. That reduced the number of errors (which was almost the entire block), but there are still errors. I can't figure out where the conflict is exactly.
[UPDATE] To my eternal shame, I believe I discovered the problem. I simply removed the configuration for intends from the ESLint configuration. I removed this:
"indent": ["error", 4, { "SwitchCase": 1 }],
"react/jsx-indent": ["error", 4],
"react/jsx-indent-props": ["error", 4],
And now it seems to be behaving normally. I assume this is because it screws up Prettier when trying to handle indents. I only needed the configuration for Prettier.
Lesson: test more by removing configurations which may be causing conflict before posting.
To make sure this is marked as solved:
I simply removed the configuration for indents from the ESLint configuration. I removed this:
"indent": ["error", 4, { "SwitchCase": 1 }],
"react/jsx-indent": ["error", 4],
"react/jsx-indent-props": ["error", 4],
And now it seems to be behaving normally. I assume this is because it screws up Prettier when trying to handle indents. I only needed the configuration for Prettier.
Lesson: test more by removing configurations which may be causing conflict before posting.
I had the same problem as mentioned in the question above, however I figured out how to solve it in a way that not only could the "indent" setting be kept, but so it can be adjusted, allowing for tabWidth to be set as you like.
First I want to note, so we're all on the same page, what the set-up I am using for linting/formatting exactly is:
Source Code Editor: V.S. Code
Linting Utility: ESLint
Opinionated Formatter: Prettier
Style-Guide: AirBnB
Additionally I also equip the following, which I download using NPM:
eslint-plugin-prettier
eslint-config-prettier
eslint-config-airbnb
For those familiar with linting while using V.S. Code, you guys know that what I am using is actually the short list. There is all kinds of other configs, plugins & extensions that can be obtained. The important thing to note here, is that I am using a tried & true setup, that allows Prettier, and ESLint to work harmoniously together.
With that said, even having a good configuration, and all the correct extensions I still had a problem with the above rule, the same as the developer who posted the question. I knew the problem had to do with ESLint's rules, and how they were being configured in my .eslintrc.json file. After much research, and near mastering ESLint, I found that I was correct. There are a few ESLint rules, (3 ESLint rules, and 1 Prettier Setting), that you need to have configured properly, however; at the same time you need to make sure your .prettierrc file settings are in-sync with your .eslintrc.json file rules. Once you understand it all, it is actually not as complicated as it sounds.
STEP #1 Know what tabWidth you want and set it in .prettierrc
First off you need to decide what you want your styles tab-width to be. (Most Style-Guides set there tab-width at (2x Space-Width), but many dev's will change there settings to a (4x Space-Width). Any thing other than 2x and 4x is considered taboo.)
Go ahead and open your .prettierrc file (or what ever mimetype of prettier configuration file you use), then set 'tabWidth' to your liking, just make sure that you stick with a consistant tabWidth from here on out, becuase ESLint needs to be in sync with prettier.
Your '.prettierrc' file should look similar to this:
{
"printWidth": 90,
"tabWidth": 4,
"useTabs": false,
"trailingComma": "all",
"singleQuote": true,
"semi": true,
"bracketSpacing": false,
}
STEP #2: set the "max-len" rule in .eslintrc.json**
open up your .eslintrc.json file (or whatever version of ESLint configuration file mime-type that you use), and set the "max-len" rule in the rules property of your eslintrc.json. The rule is not in the file by default so you will have to write it in. To see how, review the Example I Created Below.
Be sure that the "tabWidth" property within ESLint's "max-len" rule, holds exactly the same value, as the "tabWidth" setting within your .prettierrc file.
There are some other rule options here that are important to set properly as well. The first, 'code', sets the max amount of chars each line can hold, aka(max-line-length). When "code" is set ESlint will not allow more characters than what "code" has been set to. The catch is that you absolutely must Make sure that the "printWidth" setting in your .prettierrc file, which you probably will have to write in, is set to the same value as the "code" property's value in your .eslintrc.json max-len rule.
"ignoreUrls" can be set either way and make sure the rule does throw an error by leaving the word "error" as it is.
Here is an example of my max-len rule in ESLint
"rules": {
"max-len": [
"error",
{
"code": 90,
"tabWidth": 4,
"ignoreUrls": true
}
],
}
See the .prettierrc example above, to view how to set "printWidth"
STEP #3: ESLint's "no-tabs" Rule
The "no-tabs" rule, is a 'must set', w/o it your linting & formatting > can unsynchronize.
You can set "allowIndentationTabs" as you like, Allowing for, or disallowing indentation tabs won't make a difference.
What the no-tabs rule should look like:
"rules": {
"no-tabs": ["error", {"allowIndentationTabs": true}],
"max-len": [
"error",
{
"code": 90,
"tabWidth": 4,
"ignoreUrls": true
}
],
}
STEP #4: ESLint's "indent" Rule, by far the most important rule of this discussion
Seriously this one is important. Its the one that gets thrown out in an attempt to fix the switch indentation problem, which doesn't give you control over other settings, like setting your own tab-width. The "indent" rule.
First make sure indent is active by setting error to error as you see it, you could also set it to warn, but its better to set it as error so prettier knows to fix it imeadiatly. The next setting is the width of your indentations, which has to be the same exact value as your tabWidth in your .prettierrc file, and as in the "max-len" ESLint rule.
"indent": ["error", 4, {"SwitchCase": 1}],
The last settings in the brackets, "SwitchCase" can be confusing. No one explained any of this to me at first so I had to figure it out on my own, and this screwed me up a bit. The number that "SwitchCase" gets set to is not like the 4 before it. The 4 that comes before it is the initial setting of the "indent" rule and can stand alone like this:
"indent": 4; // throws error
// or
"indent": ["warn", 4] // Throws warning, which is somtimes less annoying than an error
So it is important to note that the value 4 that you see in the "indent" rule, is how many spaces an indent will be. This led me to believe that the 1 after "SwitchCase" meant how many spaces that the switch keyword case will be indented.
Example:
switch (x) {
case 1:
break;
}
That is not how it works though. The number that rule "SwitchCase" is set to, tells the editor how many times to indent the keyword 'case'. So if the "indent" rule is set to 4, and the "SwitchCase" rule is set to 4, then ESLint will expect an indentation of 4x4=16. At the end of the day ESLint will actually expect more than 16, because ESLint is going to take on all the indentation from different levels of blocks that the switch statement is found in, this ends up leading to ESLint expecting 24-36 spaces of indentation, that's crazy.
"SwitchCase" needs to be set to 1.
"rules": {
"indent": ["error", 4, {"SwitchCase": 1}],
"no-tabs": ["error", {"allowIndentationTabs": true}],
"max-len": [
"error",
{
"code": 90,
"tabWidth": 4,
"ignoreUrls": true
}
],
}
If you set all the rules right that should work for you
If it is still not working, try starting with a clean slate, delete your .eslintrc.json file, and create a new eslintrc.json file, and build it anew. You shouldn't have to start over with a new .prettierrc file.
To Wrap Up
Prettier wants to indent everything uninformed like. So if tabWidth is set to 4, and tabWidth & indent is set to 4 in ESlint then every block gets indented 4 spaces be prettier, no more and no less.
The whole problem initially is that, the style guides often ask that the keyword case not be indented, so when ESLint is setup, that is what it is configured to do by the NPM config you install upon initializing ESLint. However that does not work with prettier.
This answer wound up much longer than I thought it would. Getting Prettier, ESLint & VS Code to work harmoniously together is a very involved task, especially for first timers. I use Babel on top of this AST stack (I made that term up lol, what else would you call it?). If you want to be able to lint documents that contain TC39 ECMAScript Stage-3 Proposals, this includes features such as Private-Members, Static Methods, ect..., then you will need to use configure ESLint to use Babel's parser.

validation error on prettyPhoto's rel attribute

It is looks like W3C's validator return a validation error on prettyPhoto's rel attribute for HTML5 pages. How do I solve this error?
Bad value prettyPhoto[gallery1] for attribute rel on element a: Keyword prettyphoto[gallery1] is not registered.
Many thanks!
Using rel attribute with non-proposed (thus not allowed) values not valid for HTML5 markup. Value prettyPhoto is not in the list of proposed values. So you may face the difficulties with getting your web-page with image gallery passing validation.
A Possible Solution:
Open jquery.prettyPhoto.js (presumably non-minified one) and perform find & replace function of your text-editor: replace all occurrences of attr('rel') with attr('data-gal').
In your gallery code use:data-gal="prettyPhoto[galname]"instead of:
rel="prettyPhoto[galname]"
Initialize your prettyPhoto with:
jQuery("a[data-gal^='prettyPhoto']").prettyPhoto();
And you are on the right way for getting your code valid!
You can also read this article with this possible solution.
You can use the (undocumented) hook setting as mentioned in the comments here.
Specify your links like this: and use $("a[data-gal^='prettyPhoto'").prettyPhoto({hook: 'data-gal'}); to initialize prettyPhoto.
You can also fix it by updating the settings to use the class hook:
s = jQuery.extend({
...
hook: "rel",
animation_speed: "fast",
ajaxcallback: function() {},
slideshow: 5e3,
autoplay_slideshow: false,
opacity: .8,
...
to:
s = jQuery.extend({
...
hook: "class",
...

Can I create links with 'target="_blank"' in Markdown?

Is there a way to create a link in Markdown that opens in a new window? If not, what syntax do you recommend to do this? I'll add it to the markdown compiler I use. I think it should be an option.
As far as the Markdown syntax is concerned, if you want to get that detailed, you'll just have to use HTML.
Hello, world!
Most Markdown engines I've seen allow plain old HTML, just for situations like this where a generic text markup system just won't cut it. (The StackOverflow engine, for example.) They then run the entire output through an HTML whitelist filter, regardless, since even a Markdown-only document can easily contain XSS attacks. As such, if you or your users want to create _blank links, then they probably still can.
If that's a feature you're going to be using often, it might make sense to create your own syntax, but it's generally not a vital feature. If I want to launch that link in a new window, I'll ctrl-click it myself, thanks.
Kramdown supports it. It's compatible with standard Markdown syntax, but has many extensions, too. You would use it like this:
[link](url){:target="_blank"}
I don't think there is a markdown feature, although there may be other options available if you want to open links which point outside your own site automatically with JavaScript.
Array.from(javascript.links)
.filter(link => link.hostname != window.location.hostname)
.forEach(link => link.target = '_blank');
jsFiddle.
If you're using jQuery:
$(document.links).filter(function() {
return this.hostname != window.location.hostname;
}).attr('target', '_blank');
jsFiddle.
With Markdown v2.5.2, you can use this:
[link](URL){:target="_blank"}
So, it isn't quite true that you cannot add link attributes to a Markdown URL. To add attributes, check with the underlying markdown parser being used and what their extensions are.
In particular, pandoc has an extension to enable link_attributes, which allow markup in the link. e.g.
[Hello, world!](http://example.com/){target="_blank"}
For those coming from R (e.g. using rmarkdown, bookdown, blogdown and so on), this is the syntax you want.
For those not using R, you may need to enable the extension in the call to pandoc with +link_attributes
Note: This is different than the kramdown parser's support, which is one the accepted answers above. In particular, note that kramdown differs from pandoc since it requires a colon -- : -- at the start of the curly brackets -- {}, e.g.
[link](http://example.com){:hreflang="de"}
In particular:
# Pandoc
{ attribute1="value1" attribute2="value2"}
# Kramdown
{: attribute1="value1" attribute2="value2"}
^
^ Colon
One global solution is to put <base target="_blank">
into your page's <head> element. That effectively adds a default target to every anchor element. I use markdown to create content on my Wordpress-based web site, and my theme customizer will let me inject that code into the top of every page. If your theme doesn't do that, there's a plug-in
Not a direct answer, but may help some people ending up here.
If you are using GatsbyJS there is a plugin that automatically adds target="_blank" to external links in your markdown.
It's called gatsby-remark-external-links and is used like so:
yarn add gatsby-remark-external-links
plugins: [
{
resolve: `gatsby-transformer-remark`,
options: {
plugins: [{
resolve: "gatsby-remark-external-links",
options: {
target: "_blank",
rel: "noopener noreferrer"
}
}]
}
},
It also takes care of the rel="noopener noreferrer".
Reference the docs if you need more options.
For ghost markdown use:
[Google](https://google.com" target="_blank)
Found it here:
https://cmatskas.com/open-external-links-in-a-new-window-ghost/
I'm using Grav CMS and this works perfectly:
Body/Content:
Some text[1]
Body/Reference:
[1]: http://somelink.com/?target=_blank
Just make sure that the target attribute is passed first, if there are additional attributes in the link, copy/paste them to the end of the reference URL.
Also work as direct link:
[Go to this page](http://somelink.com/?target=_blank)
You can do this via native javascript code like so:
var pattern = /a href=/g;
var sanitizedMarkDownText = rawMarkDownText.replace(pattern,"a target='_blank' href=");
JSFiddle Code
In my project I'm doing this and it works fine:
[Link](https://example.org/ "title" target="_blank")
Link
But not all parsers let you do that.
There's no easy way to do it, and like #alex has noted you'll need to use JavaScript. His answer is the best solution but in order to optimize it, you might want to filter only to the post-content links.
<script>
var links = document.querySelectorAll( '.post-content a' );
for (var i = 0, length = links.length; i < length; i++) {
if (links[i].hostname != window.location.hostname) {
links[i].target = '_blank';
}
}
</script>
The code is compatible with IE8+ and you can add it to the bottom of your page. Note that you'll need to change the ".post-content a" to the class that you're using for your posts.
As seen here: http://blog.hubii.com/target-_blank-for-links-on-ghost/
If someone is looking for a global rmarkdown (pandoc) solution.
Using Pandoc Lua Filter
You could write your own Pandoc Lua Filter which adds target="_blank" to all links:
Write a Pandoc Lua Filter, name it for example links.lua
function Link(element)
if
string.sub(element.target, 1, 1) ~= "#"
then
element.attributes.target = "_blank"
end
return element
end
Then update your _output.yml
bookdown::gitbook:
pandoc_args:
- --lua-filter=links.lua
Inject <base target="_blank"> in Header
An alternative solution would be to inject <base target="_blank"> in the HTML head section using the includes option:
Create a new HTML file, name it for example links.html
<base target="_blank">
Then update your _output.yml
bookdown::gitbook:
includes:
in_header: links.html
Note: This solution may also open new tabs for hash (#) pointers/URLs. I have not tested this solution with such URLs.
In Laravel I solved it this way:
$post->text= Str::replace('<a ', '<a target="_blank"', $post->text);
Not works for a specific link. Edit all links in the Markdown text. (In my case it's fine)
I ran into this problem when trying to implement markdown using PHP.
Since the user generated links created with markdown need to open in a new tab but site links need to stay in tab I changed markdown to only generate links that open in a new tab. So not all links on the page link out, just the ones that use markdown.
In markdown I changed all the link output to be <a target='_blank' href="..."> which was easy enough using find/replace.
I do not agree that it's a better user experience to stay within one browser tab. If you want people to stay on your site, or come back to finish reading that article, send them off in a new tab.
Building on #davidmorrow's answer, throw this javascript into your site and turn just external links into links with target=_blank:
<script type="text/javascript" charset="utf-8">
// Creating custom :external selector
$.expr[':'].external = function(obj){
return !obj.href.match(/^mailto\:/)
&& (obj.hostname != location.hostname);
};
$(function(){
// Add 'external' CSS class to all external links
$('a:external').addClass('external');
// turn target into target=_blank for elements w external class
$(".external").attr('target','_blank');
})
</script>
You can add any attributes using {[attr]="[prop]"}
For example [Google] (http://www.google.com){target="_blank"}
For completed alex answered (Dec 13 '10)
A more smart injection target could be done with this code :
/*
* For all links in the current page...
*/
$(document.links).filter(function() {
/*
* ...keep them without `target` already setted...
*/
return !this.target;
}).filter(function() {
/*
* ...and keep them are not on current domain...
*/
return this.hostname !== window.location.hostname ||
/*
* ...or are not a web file (.pdf, .jpg, .png, .js, .mp4, etc.).
*/
/\.(?!html?|php3?|aspx?)([a-z]{0,3}|[a-zt]{0,4})$/.test(this.pathname);
/*
* For all link kept, add the `target="_blank"` attribute.
*/
}).attr('target', '_blank');
You could change the regexp exceptions with adding more extension in (?!html?|php3?|aspx?) group construct (understand this regexp here: https://regex101.com/r/sE6gT9/3).
and for a without jQuery version, check code below:
var links = document.links;
for (var i = 0; i < links.length; i++) {
if (!links[i].target) {
if (
links[i].hostname !== window.location.hostname ||
/\.(?!html?)([a-z]{0,3}|[a-zt]{0,4})$/.test(links[i].pathname)
) {
links[i].target = '_blank';
}
}
}
Automated for external links only, using GNU sed & make
If one would like to do this systematically for all external links, CSS is no option. However, one could run the following sed command once the (X)HTML has been created from Markdown:
sed -i 's|href="http|target="_blank" href="http|g' index.html
This can be further automated by adding above sed command to a makefile. For details, see GNU make or see how I have done that on my website.
If you just want to do this in a specific link, just use the inline attribute list syntax as others have answered, or just use HTML.
If you want to do this in all generated <a> tags, depends on your Markdown compiler, maybe you need an extension of it.
I am doing this for my blog these days, which is generated by pelican, which use Python-Markdown. And I found an extension for Python-Markdown Phuker/markdown_link_attr_modifier, it works well. Note that an old extension called newtab seems not work in Python-Markdown 3.x.
For React + Markdown environment:
I created a reusable component:
export type TargetBlankLinkProps = {
label?: string;
href?: string;
};
export const TargetBlankLink = ({
label = "",
href = "",
}: TargetBlankLinkProps) => (
<a href={href} target="__blank">
{label}
</a>
);
And I use it wherever I need a link that open in a new window.
For "markdown-to-jsx" with MUI v5
This seem to work for me:
import Markdown from 'markdown-to-jsx';
...
const MarkdownLink = ({ children, ...props }) => (
<Link {...props}>{children}</Link>
);
...
<Markdown
options={{
forceBlock: true,
overrides: {
a: {
component: MarkdownLink,
props: {
target: '_blank',
},
},
},
}}
>
{description}
</Markdown>
This works for me: [Page Link](your url here "(target|_blank)")