How to Detect if On Homepage to hide a button - javascript

If I have a static HTML homepage, is there a way of embedding some Javascript to see if I am on the home page? What I want to do is if a user is not on the homepage, display a "home" button on my navigation bar. So once I know if he's on the homepage I can use an if-else statement. Not familiar on how to do this in Javascript. I would do this in PHP, but due to restrictions on the project, I am not allowed to use PHP. This site is pure HTML pages.
The reason I need Javascript to detect the page, is because all of the pages, including the homepage are to be the same template (again, not my decision). If it wasn't for this I could create a template for every page but homepage. So that leaves me with the problem.
My current thought is to use something like this:
<script type="text/javascript">
var sPath = window.location.pathname;
var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
if(sPage != "index.html"){
$turnonhomelink=true;
}
else{
$turnonhomelink=false;
}
</script>
And then for the link:
<script type="text/javascript">
if ($turnonhomelink==true){
echo '<li>Home</li>';
}
else{
//echo nada
}
</script>
Besides the normal "this won't work if Javascript isn't on", is there anything I am missing?
The line I am most concerned about is this: if(sPage != "index.html")
Important to note is that this site is only 1 layer deep link-wise (all HTML pages in one directory), but is this the proper way of comparing strings in Javascript?

May i suggest that absolutly no javascriptr is required to achieve this. There are plenty of ways to do this with just css. Especially if you are on a static html page. The easy way would be to add a id to your body tag to indicate you are on the hompegae. Then add some css to make the home button invisble when on this page. Somethiong like this:
HTML:
<body id="homepage">
...
<li id='home-button'>
<a href='/index.htm'>Home</a>
</li>
...
CSS:
#homepage #home-button {
display: none;
}
This way the visistors with js disabled get the same experience as the normal visitors...

this should be fine. Also at what point in the html , would you make this check is important (for the url to contain "index.html") normally you can create a function doAfterLoad() and put a call to doAfterLoad() that can check for the url substring and then accordingly show/hide the homepage link. you can use html body onLoad event also.
ps: you dont need to follow $ prefix to a var in js even though its a valid var name:
$turnonhomelink==true

Related

Wordpress how to modify <body> tag of a page by adding extra html attributes

In wordpress is there a way to set the body tag attribute on a Page like this :
<body onBlur="window.focus()">
WP Block editor does not allow editing the page html, because it is visual editor of course.
I would use this code so I can make a popup window stay always on top.
BTW I solved the problem how to popup the window, just dont know how to make it stay on top
how to create Popup window
If there is other way let me know.
thanks #ruvee
Wrote step by step instruction here: update body tag
There is a hook you could use called wp_footer. You could add extra attributes to your body tag using pure/vanilla javascript like this:
add_action("wp_footer", "your_theme_adding_extra_attributes");
function your_theme_adding_extra_attributes(){
?>
<script>
let body = document.getElementsByTagName("body");
body[0].setAttribute("onBlur", "window.focus()");
</script>
<?php }
Code goes into the functions.php file of your active theme.
This answer has been tested on wordpress 5.8 and works.
Running it on a specific page:
Depending on which page you would need to run it on, you could use different conditional statements. For example:
Only on archive pages:
is_archive() would be a proper conditional check
Only on the index of your blog:
is_home() would be a conditional check.
Only on front page that may or may not be your blog index:
is_front_page() would be a conditional check
etc...
UPDATE (related to the second request that was not part of the first question)
If you have a page with a slug of blah and you want to modify its body tag, you could use the following snippet:
# The following code would only get executed on yourwebsite.com/blah
add_action("wp_footer", "your_theme_adding_extra_attributes");
function your_theme_adding_extra_attributes(){
if(is_page("blah")){ ?>
<script>
let body = document.getElementsByTagName("body");
body[0].setAttribute("onBlur", "window.focus()");
</script>
<?php }
}
is_pageDocs
For people who would need to add an extra class NOT an extra attributes, there is a hook called body_class and there are too many answers already on Stackoverflow, such as:
Add a custom class name to Wordpress body tag?
body class in WooCommerce
You could hook into the body class filter and do a echo for your attribute, not how filters are meant to work but it gets the job done without js.
add_filter('body_class', 'bt_add_attr_to_body');
function bt_add_attr_to_body ($classes) {
echo 'onBlur="window.focus()"';
return $classes;
}
I noticed from your comments that you would also like to limit to specific pages.
Lets say you want to to happen only on front page.
Youll need to add a if condition for front page, like this
add_filter('body_class', 'bt_add_attr_to_body');
function bt_add_attr_to_body ($classes) {
if (is_front_page()) echo 'onBlur="window.focus()"';
return $classes;
}
Based on where you want this attribute to appeare, you will need to create the appropriate condition.

Add a class attribute to certain links

I have pages on my site that go through a translation proxy. I need the displayed text in certain links to not be translated. I can add class="notranslate" to the link and the translator will skip over it no problem. However, I have hundreds of pages created before I implemented the translator and I'll have hundreds more as I keep going along—manually adding the class is not really an option.
The links I'm specifically concerned with are ones whose display text are literal URLs or email addresses. The translator doesn't touch the href attributes so the links still work as expected, but the displayed string gets mangled. For instance, in Vietnamese, "organization#domain.com" is displayed as "tổ chức#domain.com," and a link whose display text should be "domain.com/committees" is translated to "domain.com/commitaries."
So I'm looking for a solution that finds a elements whose display text contains "#" or "/" and adds class="notranslate". I don't think I need too robust a solution as I otherwise don't use the "#" or "/" in link display text often, if ever, except in these situations. I would guess this could be done with Javascript, but I'm a JS beginner at best. An option that filters content on the backend through Wordpress could also be a nice solution.
This is simple using jquery, ideally this will need to load before your translations plugin.
Note: If you have jquery already loaded as most wordpress themes already do, then you can remove the first line from this code, which includes the jquery library.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
$( document ).ready(function() {
$("a").each(function() {
let text = $(this).text();
if(text.includes("#")) {
$(this).addClass('notranslate');
}
if(text.includes("/")) {
$(this).addClass('notranslate');
}
})
});
</script>

Modify JavaScript code to use on dynamic pages

Thanks for you replies. Sorry, if it doesn't make sense I will try again, I'm probably complicating things!
I have a frameset index.html, with top.php with is just the radio stream, under that is index.php which is the full joomla website with navigation and everything.
The problem is, if users find the website via a search engine. It will take take them to just the index.php and they won't get the frameset with the top.php. I was using this code in the top.php and index.php:
if(self.location==top.location)self.location="index.html";
which works great apart from it takes the user to index.php no matter what page they were looking for via a search engine.
So I found this article (look under 'A better way' section) which shows you how to code it so if the user's content is on about-us.html, it will take you to that page but still ensure it is in the frameset.
http://scriptasylum.com/tutorials/frameredirect/frameredirect.html
I would like something like that but unfortunately with it being a Joomla website, I don't have page1.html, page2.html etc to be able to add the code and change it accordingly as per their instructions. I only have one page index.php which generates the pages dynamically 'on the fly'
So does anyone know a way I can do what I am wanting...
The frame set is at http://www.housocial.com/new/index.html
Just the joomla part http://www.housocial.com/new/index.php
Thanks again
You may extract the filename via RegExp(I'm not sure if this is what you're asking for)
if(self==top)
{
self.location="index.html?"+encodeURIComponent(location.href.match(/\w+\.html$/));
}
A more flexible solution that takes care of GET-parameters and anchors:
(
function(url,pattern,query,hash)
{
var filename=location.pathname.match(pattern);
if(filename)
{
url+=filename;
if(query && location.search)
{
url+=location.search;
}
if(hash)
{
url+=location.hash
}
location.href=url;
}
}
)('http://www.housocial.com/new/index.php/', //target-URL
/\w+\.html$/, //pattern to search for
1, //include QUERY_STRING
1 //include hash
)

Wordpress - Identifying Page Name

Have implemented a site in wordpress with 5 static pages besides the usual blog pages that are accesible through the nav menu. Now each of the page has its own jquery animations.
Since I want to write the animations code for all pages in a single file I want to get the page name in javascript and then switch to the proper animation function for that page. How to do this?
If you have access to your Wordpress template, you may output the current page's ID with the the_ID() template function: http://codex.wordpress.org/Function_Reference/the_ID
If you put this in your <head>, you could access the page ID in JavaScript afterwards:
<script>
var pageId = <?php the_ID(); ?>;
</script>
An alternative: The default theme Twenty Ten assigns a class "page-id-xx" to the <body> element by default. If your current theme does something similar, you could look for this class like this:
if ($('body').hasClass('page-id-xx')) { ... }
Use alert( document.URL ); it will tell you current url . and according to ypur requirement you can made changes.
see here

Injecting JavaScript into head element of website using Fiddler

I was thinking of using Fiddler for the following purpose...
I have a JavaScript based service I want to demonstrate to potential clients. In order to show them what their website could look like if they install (i.e. include) my script, I want to set up Fiddler on my PC, so that when fetching the client's website, the
<script type="text/JavaScript" src="myscript.js"></script>
line will be included in the HTML <head> section.
Can this be easily done with Fiddler? Could someone point me to where I may find the documentation covering that, if it is?
Thanks!
----Update----
For the time being I have resorted to using a BHO to add my script to the page. I use execScript(), upon onDocumentComplete, to run a simple piece of JavaScript which appends the .js file I need to the page. But EricLaw's pointers and jitter's answer seem like the way to go for a more complete (and elegant) way to do what I need.
If someone is interested I could upload the BHO code here.
-Thanks!
Open fiddler -> Menu Rules -> Customize Rules (or hit Ctrl+R)
The CustomRule.js file opens. Scroll down until you find the line
static function OnBeforeResponse(oSession: Session)
This is where your code goes. Here you can change the server response before the browser sees it.
The following code sample shows how to include a custom piece of jQuery code which replaces the Unanswered link in the horizontal menu with a link which serves as short cut to Unanswered jQuery Questions
I first show you the jQuery code I want to include
<script type='text/javascript'>
$(function() {
var newLink = 'Unanswered jQuery';
$('div#hmenus div.nav:first ul li:last a').replaceWith(newLink);
});
</script>
Now the fiddler code (based on code found in CustomRules.js and code samples from the FiddlerScript CookBook)
//is it a html-response and is it from stackoverflow.com
if (oSession.oResponse.headers.ExistsAndContains("Content-Type", "html") &&
oSession.HostnameIs("stackoverflow.com")) {
// Remove any compression or chunking
oSession.utilDecodeResponse();
var oBody = System.Text.Encoding.UTF8.GetString(oSession.responseBodyBytes);
// Match the jQuery script tag
var oRegEx = /(<script[^>]*jquery.min.js"><\/script>)/gi;
// replace the script tag withitself (no change) + append custom script tag
oBody = oBody.replace(oRegEx, "$1<script type='text/javascript'>$(function() {$('div#hmenus div.nav:first ul li:last a').replaceWith('Unanswered jQuery');})</script>");
// Set the response body to the changed body string
oSession.utilSetResponseBody(oBody);
}
I think you should now able to hackyourself together a piece of code which fits your problem.
Example
// Match the head end
var oRegEx = /(<\/head>)/gi;
// replace with new script
oBody = oBody.replace(oRegEx, "<script type='text/javascript' src='http://url/myscript.js'></script>$1");
if you use jQuery you can add js on the fly. I would probably think you can have a method which would include/exclude your script based on some query param. This is how you would include JS with jQuery
$.getScript('someScript.js',function(){
//Do something here after your script loads
});
Haven't tried it, but how about GreaseMonkey for IE?

Categories

Resources