I work with a function in my main page. All works fine, I just want to know how to use the function :
localStorage.setItem("language", selectedLanguage);
currentlanguage= localStorage.getItem("language");
My goal is to keep the select language in a page when i click on a link and go in another page.
For example id="en" is the language by default, but if I want to use id="fr" in my main page, and click on link who will send me in another page. I will come back to id="en". So how can I use localStorage to keep the same language ?
Here is the jsfiddle of the function that I use:
https://jsfiddle.net/kodjoe/chvw181j/
HERE IS MY HTML CODE
<a class="button" id="en">EN</a>
<a class="button" id="fr">FR</a>
<a class="button" id="de">DE</a>
<div class="lan en">1</div>
<div class="lan fr">2</div>
<div class="lan de">3</div>
<div class="lan en">4</div>
<div class="lan fr">5</div>
<div class="lan de">6</div>
HERE IS MY JS
$(document).ready(function() {
$('.lan').hide();
$('.en').show();
});
$('.button').click(function(event) {
$('.lan').hide();
var selectedLanguage = $(this).attr('id');
var setActiveLanguage = "." + selectedLanguage;
$(setActiveLanguage).show();
localStorage.setItem("language", selectedLanguage);
currentlanguage= localStorage.getItem("language");
});
HERE IS MY CSS
.button { cursor:pointer; padding: 0px 30px; }
localStorage.setItem("language", selectedLanguage);
currentlanguage= localStorage.getItem("language");
You could use SessionStorage to save your data (like selected language). Then expend your functions with if-clauses to set the right show/hide-status.
You could use localStorage, but I would just put the code in a file where you'd like to include any global scripts, since you will or already do have other scripts that are applicable to the application as a whole. Then link the file in your head (you'd likely be using an include of some sort for your header content).
<script src="js/globalScripts.js"></script>
//globalScripts.js
$(document).ready(function() {
$('.lan').hide();
$('.en').show();
});
$('.button').click(function(event) {
$('.lan').hide();
var selectedLanguage = $(this).attr('id');
var setActiveLanguage = "." + selectedLanguage;
$(setActiveLanguage).show();
});
Related
I am making an html change to a CMS that will affect all pages when the changes are live. I would like this html alert to only affect 1 specific page. I am attempting to do an if statement for the page title.
The logic is that if the page title is Test Article Two then show the html that I have put in place, if not then display=none. With this logic in place, I am viewing the html on all pages not just the one I want it to show.
<div class="container">
<div class="title-wrapper">
<span id="article-banner-country">#countryFullText</span> /
<span id="article-banner-category">#subCatText</span>
<div id="article-banner-title">#pageTitle</div>
<!--page alert -->
<div class="feedback-container content-desktop" id="alert-dialog">
<div class="feedback-left">
<p>Have any feedback? Reach out to us!</p>
</div>
<div class="feedback-right">
<button class="feedback-button">Give Feedback</button>
<button class="feedback-button">Dismiss</button>
</div>
</div>
</div>
</div>
<script>
function showAlert() {
if(#pageTitle === "Test Article Two") {
document.getElementById('alert-dialog').style.display = 'block';
}else {
document.getElementById('alert-dialog').style.display = 'none';
}
}
</script>
I'd recommend changing a class on the body element so that you can use CSS for the styling.
HTML: nothing really changed here
<body>
<div class="container">
<div class="title-wrapper">
<span id="article-banner-country">#countryFullText</span> /
<span id="article-banner-category">#subCatText</span>
<div id="article-banner-title">#pageTitle</div>
<div class="feedback-container content-desktop" id="alert-dialog">
<div class="feedback-left">
<p>Have any feedback? Reach out to us!</p>
</div>
<div class="feedback-right">
<button class="feedback-button">Give Feedback</button>
<button class="feedback-button">Dismiss</button>
</div>
</div>
</div>
</div>
</div>
</body>
javascript: just check the document.title and add the class the the body element
<script>
if(document.title === "Test Article Two") {
document.body.classList.add("show-alert");
}
</script>
Use CSS for the styling. Always hide #alert-dialog and only show it when we add the class to the body.
<style>
#alert-dialog {
display: none;
}
.show-alert #alert-dialog {
display: block;
}
</style>
If you are making static pages or using server side rendering, you could add logic to add a class to show or hide the alert element without adding more javascript to the page. It will have the relevant class(es) when the html is generated and delivered. This way you won't have to create a function, call it and manipulate the DOM after everything is rendered.
I may have missed this in the code above, are you calling the showAlert function anywhere? If not, your alert won't be shown (or will be shown depending on the default styles).
One thing I'd caution against is the imperative nature of the code here. If you wanted to reuse this alert functionality on another page, you'd have to add another more logic to detect another page title every time you wanted to use the alert. Since you are using a CMS, you might consider adding a flag to show the alert, and on this specific page, turn that flag on.
If you wanted to use the function strategy, I'd set your default alert styles:
#alert-dialog {
display: none;
}
.show {
display: block;
}
and try something like this:
<script>
function showAlert() {
if(document.title === "Test Article Two") {
document.getElementById('alert-dialog').classList.add('show');
}
}
document.addEventListener("DOMContentLoaded", showAlert);
</script>
Another alternative is to take a look at the path of the page this is supposed to be on (window.location.pathname) and using regex to see if it matches what you want. I'd recommend that over looking at the title since it's more likely the title of the page will change rather than the url.
In JavaScript, you can access the page title with document.title. You should change the script like this:
function showAlert() {
if(document.title === "Test Article Two") {
document.getElementById('alert-dialog').style.display = 'block';
} else {
document.getElementById('alert-dialog').style.display = 'none';
}
}
I have the following markup, which represents a table which have <a> inside its <td>:-
now i am trying to find a way using javascript, to show the href of all the <a class="ms-listlink"> beside them.so the <td> will contain something as follow:-
Design Transfer
http://***/buisnessfunctions/pmo/progammes/136/
instead of just showing the text:-
Design Transfer
so is there a way to achieve this?
You can do this without javascript - css has a content property that can access attributes. Here's an example:
a {
display: block;
}
a:after {
display: inline-block;
margin-left: 1em;
content: attr(href);
}
Google
Zombocom
Loop through each link, read its href property and insertAfter the link.
$('.ms-listlink').each(function(){
var link = $(this).attr('href');
$(this).insertAfter('<span>'+ link +'</span>');
});
I prefer the CSS solution above, but here's the JS solution FWIW
$('.ms-listlink').each(function() {
const href = $(this).attr('href');
const $td = $(this).closest('td');
$($td).append(href);
})
I really like the CSS answer. Tiny, easy, concise. Just in case you are curious (or for some reason require a JS-only solution), here is a way to do it in plain vanilla JavaScript (no additional libraries):
<div id=container>
<a href=https://google.com >GOOGLE </a> <span></span> <br />
<a href=https://faceboook.com >FACEBOOK </a> <span></span> <br />
<a href=https://yahoo.com >YAHOO </a> <span></span> <br />
</div>
<script>
var container = document.getElementById('container');
var anchor = container.getElementsByTagName('a');
var span = container.getElementsByTagName('span');
for(var item in anchor) {
span[item].innerHTML = anchor[item].href;
}
</script>
*NOTE: If you need the url's to be a clickable part of the hyperlinks, put the span's inside the 'a' tags.
I'm currently using the following code for my menu items:
HTML
<li>
<a id="About" class="button" href="About Us.cshtml">About Us</a>
</li>
<li style="margin-left: 30px;">
<a id="Services" class="button" href="Services.cshtml">Services</a>
</li>
<li style="margin-left: 30px;">
<a id="Contact" class="button" href="Contact Us.cshtml">Contact Us</a>
</li>
CSS
#About {background-image: url(../Buttons/About.png); width: 87px;}
#Services {background-image: url(../Buttons/Services.png); width: 112px;}
#Contact {background-image: url(../Buttons/Contact.png); width: 117px;}
a.button {height: 20px; display: inline-block; background-repeat: no-repeat}
a.button:hover {background-position: 0 -20px;}
a.button:active {background-position: 0 -40px;}
I need to get the buttons to remain in the 'active' state after they're clicked and the page loads/refreshes etc.
If the solution requires javascript, please bear in mind that I'm a rank amateur so I'll need any explanations in layman's terms (preferably with examples).
You need to identify the page you are currently on.
var page = window.location.href;
page = page.substr((page.lastIndexOf('/') + 1));
page = page.split('.');
page = page[0];
//At this point you will have the current page only with no extension or query paramaters
//I.E. "About Us"
page = page.toUpperCase();
//This accounts for upper or lower casing of urls by browsers.
switch(page) {
case "ABOUT US":
$('#About').addClass('< name of active button class >');
break;
case "SERVICES":
$('#Services').addClass('< name of active button class >');
break;
case "CONTACT US":
$('#Contact').addClass('< name of active button class >');
break;
}
If you're not using jQuery replace this line:
$('#< element name >').addClass('< name of active button class >');
with this line:
document.getElementById("< element name >").className += " < name of active button class >";
Hope this helps.
Best just to stick to using CSS classes with some JS. This way you can mix both styles for the pseudoclass (:hover) as well as the CSS class.
$('.myButtonLink').click(function() {
$(this).addClass('active_class');
});
Or if you want to toggle it.
$('.myButtonLink').click(function() {
$(this).toggleClass('active_class');
});
This way if there any changes in your layout, you only have to update the CSS styles that are apart of that class and not have to update your JavaScript code.
You can use the window or localStorage element to keep stage across page refreshes.
var key = getStorageKeyFromLink(link);
window.activeStateLookup = window.activeStateLookup || {};
window.activeStateLookup[key] = {
element : link
};
Now when your page loads you can just update all the images:
window.onload = function() {
var lookup = window.activeStateLookup || {};
for(var key in lookup) {
var element = lookup[key].element;
element.addClass('active_class');
}
}
--- EDIT ---
Here's your DEMO.
The example uses localStorage, but it would work the same with the window object. Be sure to copy and paste the code and try it out on your local machine since jsfiddle has some blocks against what's going on.
http://jsfiddle.net/GDXLb/7/
You could use a little jquery to see what the url is, parse it and then re-apply the active class to the appropriate link.
I.E ( i haven't tested this... it's more of an idea...)
var path = window.location.pathname;
$(a).each(function(){
if (path.indexOf($(this).prop("href")) > 0){
$(this).child("button").addClass("active");
break;
}
});
$('.myButtonLink').click(function() {
$(this).css('background-position', '0 0');
});
DEMO
I am new to JavaScript and actually quite desperate by now
I have an HTML file that:
gets data from an XML file and displays them in various divs (e.g. )
these divs are hidden (by default) by a class name (class='box')
when a link is clicked, I pass the 'href' to the function showContent, remove the #, and then look for an element with that ID in the document.
then I add a new class name ('show') - so that this element shows up!
If you run the code you will see that every time you click on a link a new div is displayed...
So current problems:
replace already shown divs with the new clicked ID so that only one div shows up every time.
How can I avoid inserting the onClick event in every single tag - and make this more automated?
My code is as follows:
function showContent(obj)
{
var linkTo = obj.getAttribute("href");
var newlinkTo=linkTo.replace('#','');
//alert (newlinkTo);
document.getElementById(newlinkTo).innerHTML=" This is where the xml variable content should go";
document.getElementById(newlinkTo).className += " Show";
return true;
}
<a href="#b0" onClick="return showContent(this);">
<div id="text_content"> link2 </div>
</a>
<a href="#b1" onClick="return showContent(this);">
<div id="text_content"> link 1 </div>
</a>
<div class='box' id='b0'> abstract content </div>
<div class='box' id='b1'> introduction content </div>
I'm not usually into using jQuery everywhere, but with it you could just do:
<a class='showContent' data='b0'/>
Your js:
var selected;
$('a.showContent').on('click',function(e){
var toShow = $(this).attr('data');
if(selected!==undefined) selected.removeClass('Show');
selected = $(div+'#'+toShow);
selected.addClass('Show');
});
Not sure if this is what you want, but thought I'd suggest it.
This sort of thing is not hard to do without jQuery.
I would recommend using a hash-bang (#!) for Javascript activated links to keep it separate from other possible links with hashes. (script is at the bottom)
<div id="nav-links">
<a href="#!b0">
<div id="text_content"> link2 </div>
</a>
<a href="#!b1">
<div id="text_content"> link 1 </div>
</a>
</div>
<div class='box' id='b0'> abstract content </div>
<div class='box' id='b1'> introduction content </div>
<script type="text/javascript">
var links = document.getElementById('nav-links').getElementsByTagName('a');
for(var i = 0, link; link = links[i]; i++) {
link.onclick = showContent;
// Hide content divs by default
getContentDiv(link).style.display = 'none';
}
// Show the first content div
if(links.length > 0) showContent.apply(links[0]);
var current;
function showContent() {
// hide old content
if(current) current.style.display = 'none';
current = getContentDiv(this);
if(!current) return true;
//current.innerHTML = "This is where the xml variable content should go";
current.style.display = 'block';
return true;
}
function getContentDiv(link) {
var linkTo = link.getAttribute('href');
// Make sure the link is meant to go to a div
if(linkTo.substring(0, 2) != '#!') return;
linkTo = linkTo.substring(2);
return document.getElementById(linkTo);
}
</script>
There is a WAY cleaner way to do this:
This is just my quick example, it can get EVEN cleaner than this, but this works for your case:
HTML:
link b0
link b1
<div class='box' id='b0'> abstract content </div>
<div class='box' id='b1'> introduction content </div>
CSS:
#b0 { display: none; }
#b1 { display: none; }
a, div.text_content { display: inline; padding: 0 10px; }
JQUERY:
$('.link').click(function(){
var id = $(this).attr("rel");
$('#'+id).slideToggle('slow');
});
Each link would have to have a REL attribute that is the same as the ID of the div element that you are trying to show.
Here is a JSFiddle to this example in action:
http://jsfiddle.net/CUJSM/5/
I have a a link that looks similar to this
Blog
As you can the link has an ID of 'blog' what I want to do is to create an div on the fly with the ID from the link that was clicked so if the 'blog' is clicked, then the markup would be
<div id="blog">
<!--some content here-->
</div>
Like wise if for instance the news link is clicked then I would like,
<div id="news">
<!--some content here-->
</div>
to be created in the markup if this possible? and how Im pretty new to jQuery.
Try this:
$("a").click(function(){
$("#wrapper").append("<div id=" + this.id + "></div>");
});
Not tested, should work ;)
where: #wrapper is parent element, work on all a as you see.
You will need to give the div a different ID. Perhaps you could give it a class instead:
$("#blog").click(function() {
$(this).after("<div class='blog'>...</div>");
return false;
});
That's just one of many ways to create a div. You probably also want to avoid duplicates however in which case, use something like this:
$("#blog").click(function() {
var content = $("#blog_content");
if (content.length == 0) {
content = $("<div></div>").attr("id", "blog_content");
$(this).after(content);
}
content.html("...");
return false;
});
As for how to handle multiple such links I would do something like this:
Blog
News
Weather
<div id="content"></div>
with:
$("a.content").click(function() {
$("#content").load('/content/' + this.id, function() {
$(this).fadeIn();
});
return false;
});
The point is this one event handler handles all the links. It's done cleanly with classes for the selector and IDs to identify them and it avoids too much DOOM manipulation. If you want each of these things in a separate <div> I would statically create each of them rather than creating them dynamically. Hide them if you don't need to see them.
Try This :
<a id="blog">Blog</a>
<a id="news">news</a>
<a id="test1">test1</a>
<a id="test2">test2</a>
$('a').click(function()
{
$('<div/>',{
id : this.id,
text : "you have clicked on : " + this.id
}).appendTo("#" + this.id);
});
First of all you should not make 2 elements with same ID. At your example a and div will both have id="blog". Not XHTML compliant, plus might mess up you JS code if u refernce them.
Here comes non-jquery solution (add this within script tags):
function addDiv (linkElement) {
var div = document.createElement('div');
div.id = linkElement.id;
div.innerHTML = '<!--some content here-->';
document.body.appendChild(div); // adds element to body
}
Then add to HTML element an "event handler":
Blog
This question describes how to create a div. However, you shouldn't have two elements with same IDs. Is there any reason why you can't give it an id like content_blog, or content_news?
Unfortunately if you click on a link the page you go to has no idea what the idea of the link you clicked was. The only information it knows is what's contained in the URL. A better way to do this would be to use the querystring:
Blog
Then using the jQuery querystring plugin you could create the div like:
$("wrapper").add("div").attr("id", $.query.get("id"));
You shouldn't have elements in your page with the same ID. Use a prefix if you like, or perhaps a class.
However, the answer is as follows. I am imagining that your clickable links are within a div with the ID "menu", and your on-the-fly divs are to be created within a div with the ID "content".
$('div#menu a').click(function(){
$('div#content').append('<div id="content_'+this.id+'"><!-- some content here --></div>');
});
Any problems, ask in the comments!
Also the following statement is available to create a div dynamically.
$("<div>Hello</div>").appendTo('.appendTo');
Working fiddle: https://jsfiddle.net/andreitodorut/xbym0bsu/
you can try this code
$('body').on('click', '#btn', function() {
$($('<div>').text('NewDive').appendTo("#old")).fadeOut(0).fadeIn(1000);
})
#old > div{
width: 100px;
background: gray;
color: white;
height: 20px;
font: 12px;
padding-left: 4px;
line-height: 20px;
margin: 3px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
<link rel="stylesheet" href="./index.css">
</head>
<body>
<div>
<!-- Button trigger modal -->
<button type="button" id="btn">Create Div</button>
<div id="old">
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>
</html>