So I've got this code in my page: a very simple but working script to translate it to several languages.
// preparing language file
var aLangKeys=new Array();
aLangKeys['en']=new Array();
aLangKeys['es']=new Array();
aLangKeys['fr']=new Array();
aLangKeys['cn']=new Array();
aLangKeys['en']['language']='english';
aLangKeys['es']['language']='español';
aLangKeys['fr']['language']='français';
aLangKeys['cn']['language']='中文';
aLangKeys['en']['buy']='buy';
aLangKeys['es']['buy']='comprar';
aLangKeys['fr']['buy']='acheter';
aLangKeys['cn']['buy']='买';
$(document).ready(function() {
// onclick behavior
$('.language').click(function() {
var lang = $(this).attr('id'); // obtain language id
if ($(this).attr('id') == 'es') {
$('.language').attr('id', 'fr');
}
else if ($(this).attr('id') == 'fr') {
$('.language').attr('id', 'cn');
}
else if ($(this).attr('id') == 'cn') {
$('.language').attr('id', 'en');
}
else if ($(this).attr('id') == 'en') {
$('.language').attr('id', 'es');
}
// translate all translatable elements
$('.translate').each(function(i){
$(this).html(aLangKeys[lang][ $(this).attr('key') ]);
});
} );
});
// HERE'S WHERE MY BRAIN STARTS MALFUNCTIONING
if ((window.location.pathname).split('/')[1] == 'es') {
// <-- EXECUTE FUNCTION ABOVE TO TRANSLATE TO SPANISH BASED ON PATHNAME
}
else if ((window.location.pathname).split('/')[1] == 'fr') {
// <-- EXECUTE FUNCTION ABOVE TO TRANSLATE TO FRENCH BASED ON PATHNAME
}
else {
}
So it basically translates (changes the value of certain elements on the page) when clicking a button. Every time you click on it, changes to the next language. That works fine.
THE PROBLEM is, I want it 'automatically' changed to a certain language if the user is visiting from a certain link:
Example:
www.mysite.com (nothing happens because nothing is on the pathname)
www.mysite.com/es/ ('automatically changes values to spanish')
www.mysite.com/fr/ ('automatically changes values to french')
I tried 'faking' the button click with javascript but didnt work.
Also tried 'naming' the translating function and 'call/run' it.
I know it's easier to do and I'm making it complicated but I'm such a noob.
Please, help. Or just a hint. Thanks in advance and sorry for my English.
Based on code above a couple thoughts:
1) lets change aLangKeys to an object with each key being another object.
i.e.
var aLangKeys={};
aLangKeys['en']={}; // Thats a named key/prop so we want an object here
...
aLangKeys['en']['language']='english'; // ditto the above comment
2) we probably want to move the logic that checks for locality inside the ready function.
I.e.
$(document).ready(function() {
// onclick behavior
$('.language').click(function() {
...
});
// we want access to the DOM *and* maybe certain functions that do stuff. So its gotta be in here...
if ((window.location.pathname).split('/')[1] == 'es') {
// <-- EXECUTE FUNCTION ABOVE TO TRANSLATE TO SPANISH BASED ON PATHNAME
}
else if ((window.location.pathname).split('/')[1] == 'fr') {
// <-- EXECUTE FUNCTION ABOVE TO TRANSLATE TO FRENCH BASED ON PATHNAME
}
}); // end of ready function
Couple reasons:
a) we want to change the page content based on info like pathname/locality. So we want to know the page is loaded first.
b) perhaps we will want to make a function that does language processing/changing and call that from multiple places. We want that function in scope of our locality checking logic. If we define that inside the ready function scope, we will need any logic that calls that function also inside the same scope
Related
Good evening,
i was working on a part of what i hope will be my future website and i wanted to add a "photograpy" section to it, and here comes the problem.
since the title in the main page constatly changes color, i'd like to grab its current color to transfer it to the title of the other page to play an animation later on.
the problem is that when i press the related button, i am taken to the photograpy page, but the title remains black.
i've tried seraching for help on google but i haven't been able to find much.
here is the JS
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", function() {
loaded();
});
} else if (document.attachEvent) {
document.attachEvent("onreadystatechange", function() {
loaded();
});
}
function loaded() {
document.getElementById("PHtitle").style.color === titlecolor;
}
function script() {
const titlecolor = document.getElementById("title").style.color;
};
document.getElementById('photograpy').onclick = function () {
script();
};
The snippets don't allow for localStorage, so here is just the javascript.
First, I let the variables outside of a function. The titleColor function checks to see if titleColor was saved in localStorage, if not the default color is black.
Then I set the color of the phtitle to the contents of titleColor variable.
In the script function, I set the localStorage variable to the getComputedStyle color of the title.
Then last I use an event listener on the button to run the script for saving the color.
LocalStorage is a way to store data in the user's browser until they close their browser/clear their data etc.. Which will allow it to be usable on different pages then where it was saved.
let titleColor = localStorage.getItem("titleColor") || "#000000";
let PHtitle = document.querySelector("#PHtitle");
let title = document.querySelector("#title");
let btn = document.querySelector("#photography");
if(PHtitle){
PHtitle.style.color = titleColor;
}
function script() {
localStorage.setItem("titleColor", getComputedStyle(title).color)
}
if(btn && title){
btn.addEventListener("click", function() {
script();
})
}
How do I hide a div on all posts except posts on category pages in WordPress?
I currently have the following jQuery but can't get it to work -
jQuery(function(){
if (window.location.pathname == "offonalim.com/category/fashion.html"||window.location.pathname == "offonalim.com/category/interior.html"||window.location.pathname == "offonalim.com/category/travel.html"||window.location.pathname == "offonalim.com/category/work.html") {
jQuery('.qodef-post-title').show();
jQuery('.qodef-post-info').show();
} else {
jQuery('.qodef-post-title').hide();
jQuery('.qodef-post-info').hide();
}
});
I can see that category pages of your website contains the keyword "Category" in each url,
so you can use this keyword to check if the url is having this particular keyword then show or hide divs accordingly
No need to specify full urls.
<script type="text/javascript">
function myFunction(){
val path=window.location.pathname;
if(window.location.href.indexOf("category") > -1) {
$('.qodef-post-title').show();
$('.qodef-post-info').show();
} else {
$('.qodef-post-title').hide();
$('.qodef-post-info').hide();
}
}
myFunction();
</script>
window.location.pathname yields the pathname, not the entire URL. So, your code is logically incorrect.
And instead of checking for each path individually, an ideal practice would be to create an array of possible paths and check the location's path in that array. Something like this should work fine:
var catPaths = [
"/category/fashion.html",
"/category/interior.html",
"/category/travel.html",
"/category/work.html"
];
jQuery(function() {
if (catPaths.includes(window.location.pathname)) {
jQuery('.qodef-post-title').show();
jQuery('.qodef-post-info').show();
} else {
jQuery('.qodef-post-title').hide();
jQuery('.qodef-post-info').hide();
}
});
You can further minimize the code by using toggle() and grouping the selectors:
jQuery(function() {
var includes = catPaths.includes(window.location.pathname);
jQuery('.qodef-post-title, .qodef-post-info').toggle(includes);
});
Writing the code i am stuck with one thing. I am loading variable string through jQuery load function and there is where trouble starts. I want my code to check if string loaded through text file had any changes and if that is true make some actions. How do I set my variable as a string to compare it with the one in file? Part of the code
var follow, donate;
var auto_refresh = setInterval(function() {
follow = $('#followerid').load("../Muxy/most_recent_follower.txt");
donate = $('#donatorid').load("../Muxy/most_recent_donator.txt");
}, 100);
and then I want to make something like this:
someUpdateFunction() {
if($(#'followerid').get("innerHTML") != follow)
// actions (animations, div changes etc.)
}
That is probably totally wrong but I wasnt able to find any tips here. Thanks in advance
Try something like this:
$.get('../Muxy/most_recent_follower.txt', function (data) {
var followerid = $('#followerid').html();
if( followerid == data ){
// They are the same
}else{
// They are not the same
}
});
The .html() method will get the HTML inside #followerid. It sounds like that's what you want.
The jQuery.load function doesn't return the loaded file, it returns the element. Try out this:
var auto_refresh = setInterval(function() {
oldFollow = $('#followerid').html();
$('#followerid').load("../Muxy/most_recent_follower.txt");
oldDonate = $('#donatorid').html();
$('#donatorid').load("../Muxy/most_recent_donator.txt");
}, 100);
someUpdateFunction() {
if($('#followerid').html() !== oldFollow)
// actions (animations, div changes etc.)
}
}
I've created a Backbone, Marionette and Require.js application and am now trying to add smooth transitioning between regions.
To do this easily* ive decided to extend the marionette code so it works across all my pages (theres a lot of pages so doing it manually would be too much)
Im extending the marionette.region open and close function. Problem is that it now doesnt call the onClose function inside each of my views.
If I add the code directly to the marionette file it works fine. So I'm probably merging the functions incorrectly, right?
Here is my code:
extendMarrionette: function () {
_.extend(Marionette.Region.prototype, {
open : function (view) {
var that = this;
// if this is the main content and should transition
if (this.$el.attr("id") === "wrapper" && document.wrapperIsHidden === true) {
this.$el.empty().append(view.el);
$(document).trigger("WrapperContentChanged")
} else if (this.$el.attr("id") === "wrapper" && document.wrapperIsHidden === false) {
$(document).on("WrapperIsHidden:open", function () {
//swap content
that.$el.empty().append(view.el);
//tell router to transition in
$(document).trigger("WrapperContentChanged");
//remove this event listener
$(document).off("WrapperIsHidden:open", that);
});
} else {
this.$el.empty().append(view.el);
}
},
//A new function Ive added - was originally inside the close function below. Now the close function calls this function.
kill : function (that) {
var view = this.currentView;
$(document).off("WrapperIsHidden:close", that)
if (!view || view.isClosed) {
return;
}
// call 'close' or 'remove', depending on which is found
if (view.close) {
view.close();
}
else if (view.remove) {
view.remove();
}
Marionette.triggerMethod.call(that, "close", view);
delete this.currentView;
},
// Close the current view, if there is one. If there is no
// current view, it does nothing and returns immediately.
close : function () {
var view = this.currentView;
var that = this;
if (!view || view.isClosed) {
return;
}
if (this.$el.attr("id") === "wrapper" && document.wrapperIsHidden === true) {
this.kill(this);
} else if (this.$el.attr("id") === "wrapper" && document.wrapperIsHidden === false) {
//Browser bug fix - needs set time out
setTimeout(function () {
$(document).on("WrapperIsHidden:close", that.kill(that));
}, 10)
} else {
this.kill(this);
}
}
});
}
Why don't you extend the Marionette.Region? That way you can choose between using your custom Region class, or the original one if you don't need the smooth transition in all cases. (And you can always extend it again if you need some specific behavior for some specific case).
https://github.com/marionettejs/backbone.marionette/blob/master/docs/marionette.region.md#region-class
var MyRegion = Marionette.Region.extend({
open: function() {
//Your open function
}
kill: function() {
//Your kill function
}
close: function() {
//Your close function
}
});
App.addRegions({
navigationRegion: MyRegion
});
Perhaps your issue is that you are not passing a function to your event listener, but instead calling the code directly in the code below.
setTimeout(function(){
$(document).on("WrapperIsHidden:close", that.kill(that));
}, 10)
It is likely that you want something like this:
setTimeout(function(){
$(document).on("WrapperIsHidden:close", function (){ that.kill(that); });
}, 10)
Another possible problem is that you are mixing up your references to this/that in your kill function. It seems like you probably want var view to either be assigned to that.view or to use this rather than that throughout the method.
Answer to your additional problems:
You should try passing the view variable from the close function directly into your kill function because the reference to currentView is already changed to the new view object when you actually want to old view object. The reason this is happening is that you are setting a timeout before executing the kill function. You can see this if you look at the show source code. It expects close, open and then currentView assignment to happen synchronously in order.
I am working with a page that has multiple divs that toggle. This function works. A search function was added and this works too.
The problem with the page as it exists currently: The search bar was placed on the "default" div and the results load below the bar into another div that is invisible when empty. The results div is inside this first default div. If you toggle to another div, you lose the default div and can't get back to it.
For this reason, I moved the search bar to the left navigation where the other toggle links are situated. I also moved the search results div out of the default div to "stand on its own."
What I am trying to do: Make the search button show the div with the results as well as find the results. Basically, to integrate the search function into the array/toggle function. The search function is in one .js file and the toggle function is in a different .js file.
I keep thinking there must be a way to get "onclick" to call from both .js files so that I don't have to do a bunch of extra work combining the two functions that already exist and work separately. I am a Javascript newbie learning by examples and haven't been able to figure this out. I have never seen a working example of this and my searches haven't produced one.
I would be very grateful for any help. Hope I explained the problem adequately.
Edit: Here is the code I already have for the toggle function.
var ids=new Array('a','b','c',[and so on--search results not added here yet]);
function switchid(id_array){
hideallids();
for( var i=0, limit=id_array.length; i < limit; ++i)
showdiv(id_array[i]);
}
function hideallids(){
for (var i=0;i<ids.length;i++){
hidediv(ids[i]);
}
}
function hidediv(id) {
//safe function to hide an element with a specified id
if (document.getElementById) { // DOM3 = IE5, NS6
document.getElementById(id).style.display = 'none';
}
else {
if (document.layers) { // Netscape 4
document.id.display = 'none';
}
else { // IE 4
document.all.id.style.display = 'none';
}
}
}
function showdiv(id) {//safe function to show an element with a specified id
if (document.getElementById) { // DOM3 = IE5, NS6
document.getElementById(id).style.display = 'block';
}
else {
if (document.layers) { // Netscape 4
document.id.display = 'block';
}
else { // IE 4
document.all.id.style.display = 'block';
}
}
}
function initialize(){
var t = gup("target");
if( t )
{
switchid([t]);
}
}
function gup( name )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null ){
return "";
} else {
return results[1];
}
}
Thanks in advance!
When your toggle function code is loaded, the functions are declared in the Global scope. When you search functions are loaded, they are also in the Global scope. Since they are in the same scope, even though it's a different file, the toggle functions can be used by your search function, if you include the file with the search function after the file with the toggle function.
TL;DR
function search(...) {
// do your search stuff
// when you get a result ID, toggle it from here
hideallids();
showdiv(id);
}
I seriously recommend you use meaningful names, objects as namespaces to organize your code, and CamelCase or underscores to mark word boundaries in identifiers. For example:
window.ZESearch = {
'initialize' : function() { ... },
'search': function() {
// Find the node with the desired result
ZESearch.showResult(id);
},
'hideAllResults': function() { ... },
'hideResult' : function(id) { ... },
'showResult' : function(id) { ... },
...
};
ZESearch.initialize();
Since you're just learning, I've avoided the complexity of the this keyword, presented a simple way to create an object to keep your code organized but added your object to window so you can get it from anywhere in your code.