I have a school assignment to create a one page html static.
I want to have some buttons to change the language but I don't want any addition like "index.html/en/" or "index.html?lang=en". I prefer to have it with CSS only but I don't know whether it is possible or not.
In short I just want a simply bilingual "index.html" and have buttons to change the content text.
I am new in html scripting so I'm looking for some sample code or some detailed tutorial will be help.
I suggest using JS/jQuery for that:
Have language mapping for each element that will be translated:
// Translations object:
var translations = {
'en': {
'home': 'Home',
'back': 'Back'
/* ... */
},
'lt': {
'home': 'Pradžia',
'back': 'Atgal'
/* ... */
}
};
// wait for all DOM elements to load
$(document).ready(function() {
// when button is clicked
$('.lang-btn').click(function() {
// take translations subset
var lang = translations[$(this).data('lang')];
// for each element that has "data-key" attribute
$('[data-key]').each(function() {
// change it's content to other language
$(this).text(lang[$(this).data('key')]);
})
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="my-page">
Language:
<button class="lang-btn" data-lang="en">En</button>
<button class="lang-btn" data-lang="lt">Lt</button>
<hr/>
Home
<button data-key="back">Back</button>
</div>
This code is not checking if there is such translation or not. You can improve this algo with fallback to English.
For SEO reasons I'd prefer to use /en/. Use a .htaccess file with mod_rewrite.
See here Create beautiful url’s with mod_rewrite
If it is just one page, so I assume the contain is not much. Try something simpler like:
function en() {
document.getElementById("content").innerHTML = "Example";
}
function de() {
document.getElementById("content").innerHTML = "Beispiel";
}
<div id="content">sample</div>
<button onclick="en()">English</button>
<button onclick="de()">German</button>
Related
I am trying to implement accessibility option on my page that would change CSS to different file when accessibility button would be clicked.
For now, all my templates extends base_generic.html, where style.css is loaded. When accessibility button would be clicked, I wish for it to change to use style_access.css for that user. How can I accomplish that?
I think a way could be, to refer in the HTML template to both CSS files, and use an onclick function with javascript, and jquery to change the id or class of the specific elements of the template.
So for example,
let's say I wanted onclick to change the CSS of an element, I could make a counter and toggle between two ids that I will have referenced in my CSS file or files.
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<button>This is a div</button>
<h1 class="potatoe" id="hello">HELLO THIS IS TEXT</h1>
<style>
#hello { color: red; }
#bye { color: blue; }
</style>
<script>
var clickCount = 0;
$("button").on("click", function() {
clickCount++;
$(".potatoe").attr("id", clickCount % 2 === 0 ? "bye" : "hello");
});
</script>
</body>
As you'll see everytime you click the button the CSS of the element will change
This is not exactly changing between CSS files but it ultimately changes the CSS of the elements you want to select.
You can implement by using JavaScript more easily:
const toggleButton = document.getElementById('button');
const workContainer = document.getElementById('work');
toggleButton.addEventListener('click', () => {
document.body.classList.toggle('blue');
toggleButton.classList.toggle('active');
workContainer.classList.toggle('blue');
if(document.body.classList.contains('blue')){
localStorage.setItem('blue', 'enabled');
}else{
localStorage.setItem('blue', 'disabled');
}
});
if(localStorage.getItem('blue') == 'enabled'){
document.body.classList.toggle('blue');
toggleButton.classList.toggle('active');
workContainer.classList.toggle('blue');
}
I am working with a Web Form (html) and a CSS file and I wanna know what do I need to write in the CSS to make an action on one class or id- affect an other class or id. For example: I have a
<p class="hh">
Hello!
</p>
(^^ this p tag's class is "hh")
And another one:
<p class="gb">
Goodbye!
</p>
(^^ this p tag's class is "gb")
I wanna write something in the CSS file so that whenever I click on whatever there is in the "hh" class, it will make something change in the "gb" class, so if I click on the text "Hello!" it will make the color of the text "Goodbye!" green. Please help me! I try to find out how to do it for a long long time...
Thank you!
This sounds more like you need a javascript solution. In general you are not really able to change something on a click event in CSS. Consider following solution:
const hh = document.getElementById("hh");
const gb = document.getElementById("gb");
hh.addEventListener("click", function() {
gb.style.color = "green";
});
gb.addEventListener("click", function() {
hh.style.color = "red";
});
<div id="hh">
Hello!
</div>
<div id="gb">
Goodbye!
</div>
A common practice for doing this is by using JavaScript, which is known as the programming language of the web. If you've never used JavaScript before it can be a little bit confusing but if you have experience in other general purpose programming languages such as Python or Java then it shouldn't take much time to pick up.
To do what you are asking, there are a few possible ways to do this. I will share what I believe to be the most simple although not the most robust. You can use JavaScript events to fire off certain functions when certain particular things happen to your elements. For example, you can modify your HTML like so:
<p class="hh" onclick="doSomething()">Hello!</p>
Then, either in a separate JavaScript file linked back to your html file or in the of your html file, you would define the doSomething() function:
function doSomething(){
document.getElementsByClassName("gb")...
}
The document.getElementsByClassName() function is one way to select HTML elements from a page and modify it via JavaScript, I suggest checking out the very good JavaScript tutorials on W3Schools for more and better ways to do this, but this is the general principal. You would then modify the HTML element any way you need to.
Hope this helps!
You need to do that using JavaScript. I have attached a example for that.
$(".one").on('click', function() {
$(".two").css('color', 'red');
})
.one{
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="one"> Change below text to RED </p>
<p class="two"> Black text </p>
There is a way to use a :focus state to change the look of parents, but it wouldn't be possible to differentiate between which click caused the parent to focus.
Here's a simple example using JavaScript and jQuery.
var helloEls = document.querySelectorAll('#jsTest .hh');
var goodbyeEls = document.querySelectorAll('#jsTest .gb');
helloEls.forEach(function(elem) {
elem.addEventListener("click", function() {
goodbyeEls.forEach(function(el) {
if (el.className==='gb active'){
el.className = 'gb';
} else {
el.className = 'gb active';
}
});
});
});
var gbEls = $('#jqueryTest .gb');
$('#jqueryTest .hh').click(function(){
if (gbEls.hasClass('active')){
gbEls.removeClass('active');
} else {
gbEls.addClass('active');
}
});
.gb.active {
color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="jsTest">
<p class="hh">
Hello!
</p>
<p class="gb">
Goodbye!
</p>
</div>
<div id="jqueryTest">
<p class="hh">
Hello!
</p>
<p class="gb">
Goodbye!
</p>
</div>
I have a chat on my website that reads from a JSON file and grabs each message and then displays it using Vue.js. However, my problem is that when a user posts a link, it is not contained in an anchor tag <a href=""/>. Therefore it is not clickable.
I saw this post, and I think something like this would work, however, I am not allowed to add any more dependencies to the site. Would there be a way for me to do something similar to this without adding more dependencies?
Code for displaying the message.
<p v-for="msg in messages">
<em class="plebe">
<b> [ {{msg.platform.toUpperCase()}} ]
<span style="color: red" v-if="msg.isadmin">{{msg.user.toUpperCase()}}</span>
<span style="color: #afd6f8" v-else="">{{msg.user.toUpperCase()}}</span>
</b>
</em>:
{{msg.message}}
</p>
In a situation like this, its preferred to write a custom functional component.
The reason for this is the fact that we are required to emit a complex html structure, but we have to make sure to properly protect against xss attacks (so v-html + http regex is out of the picture)
We are also going to use render functions, because render functions have the advantage to allow for javascript that generates the html, having more freedom.
<!-- chatLine.vue -->
<script>
export default {
functional: true,
render: function (createElement, context) {
// ...
},
props: {
line: {
type: String,
required: true,
},
},
};
</script>
<style>
</style>
We now need to think about how to parse the actual chat message, for this purpose, I'm going to use a regex that splits on any length of whitespace (requiring our chat urls to be surrounded with spaces, or that they are at the start or end of line).
I'm now going to make the code in the following way:
Make a list for child componenets
Use a regex to find url's inside the target string
For every url found, do:
If the match isn't at the start, place the text leading from the previous match/start inside the children
place the url inside the list of children as an <a> tag, with the proper href attribute
At the end, if we still have characters left, at them to the list of children too
return our list wrapped inside a P element
Vue.component('chat-line', {
functional: true,
// To compensate for the lack of an instance,
// we are now provided a 2nd context argument.
// https://vuejs.org/v2/guide/render-function.html#createElement-Arguments
render: function (createElement, context) {
const children = [];
let lastMatchEnd = 0;
// Todo, maybe use a better url regex, this one is made up from my head
const urlRegex = /https?:\/\/([a-zA-Z0-9.-]+(?:\/[a-zA-Z0-9.%:_()+=-]*)*(?:\?[a-zA-Z0-9.%:_+&/()=-]*)?(?:#[a-zA-Z0-9.%:()_+=-]*)?)/g;
const line = context.props.line;
let match;
while(match = urlRegex.exec(line)) {
if(match.index - lastMatchEnd > 0) {
children.push(line.substring(lastMatchEnd, match.index));
}
children.push(createElement('a', {
attrs:{
href: match[0],
}
}, match[1])); // Using capture group 1 instead of 0 to demonstrate that we can alter the text
lastMatchEnd = urlRegex.lastIndex;
}
if(lastMatchEnd < line.length) {
// line.length - lastMatchEnd
children.push(line.substring(lastMatchEnd, line.length));
}
return createElement('p', {class: 'chat-line'}, children)
},
// Props are optional
props: {
line: {
required: true,
type: String,
},
},
});
var app = new Vue({
el: '#app',
data: {
message: 'Hello <script>, visit me at http://stackoverflow.com! Also see http://example.com/?celebrate=true'
},
});
.chat-line {
/* Support enters in our demo, propably not needed in production */
white-space: pre;
}
<script src="https://unpkg.com/vue#2.0.1/dist/vue.js"></script>
<div id="app">
<p>Message:</p>
<textarea v-model="message" style="display: block; min-width: 100%;"></textarea>
<p>Output:</p>
<chat-line :line="message"></chat-line>
</div>
You can watch or write computed method for the variable having url and manupulate it to html content and then use v-html to show html content on the page
v-html
I've created a html page and in that page I have forms, drop down lists and radio tags and tables. from one button I wanted to reset everything on the page when its clicked upon.
you can use the following JavaScript method to clear the HTML input file control's value:
function clearFileInputField(tagId) {
document.getElementById(tagId).innerHTML =
document.getElementById(tagId).innerHTML;
}
Or, if refactored in jQuery, this should work as well:
$("#control").html($("#control").html())
Or, for textbox type
var elements = document.getElementsByTagName("input");
for (var ii=0; ii < elements.length; ii++) {
if (elements[ii].type == "text") {
elements[ii].value = "";
}
}
You could use a reset button, please refer to this page for more information -> LINK
But if you have multiple form on the page you can write a javascript function to reset all of them like this:
$('#yourResetButton').click(function(){
$('form').each(function(idx, obj){
obj.reset();
});
});
You could also refresh your page as stated in other answers but in my opinion that could be very disappointing for your users to see that the page is refreshing
A little working fiddle as example
You can reset with reset however you won't be able to reset your inputs that doesn't included into forms, otherwise you can clear inputs within your forms like:
$('form').each(function (index, obj) { obj.reset(); });
Example
<input type="button" onclick="function() {window.location.href = window.location.href;}" name="Reset" value="Reset">
When I use the HTML <base> tag to define a base URL for all relative links on a page, anchor links also refer directly to the base URL. Is there a way to set the base URL that would still allow anchor links to refer to the currently open page?
For example, if I have a page at http://example.com/foo/:
Current behaviour:
<base href="http://example.com/" />
bar <!-- Links to "http://example.com/bar/" -->
baz <!-- Links to "http://example.com/#baz" -->
Desired behaviour:
<base href="http://example.com/" />
bar <!-- Links to "http://example.com/bar/" -->
baz <!-- Links to "http://example.com/foo/#baz" -->
I found a solution on this site: using-base-href-with-anchors that doesn't require jQuery, and here is a working snippet:
<base href="https://example.com/">
/test
Anchor
Or without inline JavaScript, something like this:
document.addEventListener('DOMContentLoaded', function(){
var es = document.getElementsByTagName('a')
for(var i=0; i<es.length; i++){
es[i].addEventListener('click', function(e) {
e.preventDefault()
document.location.hash = e.target.getAttribute('href')
})
}
})
Building upon James Tomasino's answer, this one is slightly more efficient, solves a bug with double hashes in the URL and a syntax error.
$(document).ready(function() {
var pathname = window.location.href.split('#')[0];
$('a[href^="#"]').each(function() {
var $this = $(this),
link = $this.attr('href');
$this.attr('href', pathname + link);
});
});
A little bit of jQuery could probably help you with that. Although base href is working as desired, if you want your links beginning with an anchor (#) to be totally relative, you could hijack all links, check the href property for those starting with #, and rebuild them using the current URL.
$(document).ready(function () {
var pathname = window.location.href;
$('a').each(function () {
var link = $(this).attr('href');
if (link.substr(0,1) == "#") {
$(this).attr('href', pathname + link);
}
});
}
Here's an even shorter, jQuery based version I use in a production environment, and it works well for me.
$().ready(function() {
$("a[href^='\#']").each(function() {
this.href = location.href.split("#")[0] + '#' + this.href.substr(this.href.indexOf('#')+1);
});
});
You could also provide an absolute URL:
<base href="https://example.com/">
test
Rather than this
test
I'm afraid there is no way to solve this without any server-side or browser-side script. You can try the following plain JavaScript (without jQuery) implementation:
document.addEventListener("click", function(event) {
var element = event.target;
if (element.tagName.toLowerCase() == "a" &&
element.getAttribute("href").indexOf("#") === 0) {
element.href = location.href + element.getAttribute("href");
}
});
<base href="https://example.com/">
/test
#test
It also works (unlike the other answers) for dynamically generated (i.e. created with JavaScript) a elements.
If you use PHP, you can use following function to generate anchor links:
function generateAnchorLink($anchor) {
$currentURL = "//{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
$escaped = htmlspecialchars($currentURL, ENT_QUOTES, 'UTF-8');
return $escaped . '#' . $anchor;
}
Use it in the code like that:
baz
To prevent multiple #s in a URL:
document.addEventListener("click", function(event) {
var element = event.target;
if (element.tagName.toLowerCase() == "a" &&
element.getAttribute("href").indexOf("#") === 0) {
my_href = location.href + element.getAttribute("href");
my_href = my_href.replace(/#+/g, '#');
element.href = my_href;
}
});
My approach is to search for all links to an anchor, and prefix them with the document URL.
This only requires JavaScript on the initial page load and preserves browser features like opening links in a new tab. It also and doesn't depend on jQuery, etc.
document.addEventListener('DOMContentLoaded', function() {
// Get the current URL, removing any fragment
var documentUrl = document.location.href.replace(/#.*$/, '')
// Iterate through all links
var linkEls = document.getElementsByTagName('A')
for (var linkIndex = 0; linkIndex < linkEls.length; linkIndex++) {
var linkEl = linkEls[linkIndex]
// Ignore links that don't begin with #
if (!linkEl.getAttribute('href').match(/^#/)) {
continue;
}
// Convert to an absolute URL
linkEl.setAttribute('href', documentUrl + linkEl.getAttribute('href'))
}
})
You can use some JavaScript code inside the tag that links.
<span onclick="javascript:var mytarget=((document.location.href.indexOf('#')==-1)? document.location.href + '#destination_anchor' : document.location.href);document.location.href=mytarget;return false;" style="display:inline-block;border:1px solid;border-radius:0.3rem"
>Text of link</span>
How does it work when the user clicks?
First it checks if the anchor (#) is already present in the URL. The condition is tested before the "?" sign. This is to avoid the anchor being added twice in the URL if the user clicks again the same link, since the redirection then wouldn't work.
If there is sharp sign (#) in the existing URL, the anchor is appended to it and the result is saved in the mytarget variable. Else, keep the page URL unchanged.
Lastly, go to the (modified or unchanged) URL stored by the mytarget variable.
Instead of <span>, you can also use <div> or even <a> tags.
I would suggest avoiding <a> in order to avoid any unwanted redirection if JavaScript is disabled or not working, and emulate the look of your <a> tag with some CSS styling.
If, despite this, you want to use the <a> tag, don't forget adding return false; at the end of the JavaScript code and set the href attribute like this <a onclick="here the JavaScript code;return false;" href="javascript:return false;">...</a>.
From the example given in the question. To achieve the desired behavior, I do not see the need of using a "base" tag at all.
The page is at http://example.com/foo/
The below code will give the desired behaviour:
bar <!-- Links to "http://example.com/bar/" -->
baz <!-- Links to "http://example.com/foo/#baz" -->
The trick is to use "/" at the beginning of string href="/bar/".
If you're using Angular 2 or later (and just targeting the web), you can do this:
File component.ts
document = document; // Make document available in template
File component.html
<a [href]="document.location.pathname + '#' + anchorName">Click Here</a>