Add a class attribute to certain links - javascript

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>

Related

Send a Google Analytics event when a specific text string is present on a page

I have somewhere on website a specific text, let's say "NewYork", and I want to fire a Google Analytics event to track all the occurrences of this string.
For example if a visitor come to a webpage that contain the string 'NewYork', I want to send a Google Analytics event.
Text string is in a span tag as <span class="city">NewYork</span>
I do not know any JavaScript codes, just tried the following code adapted from someone else. And it is not working at all.
<script>
var htmlString = $('body').html().toString();
var index = htmlString.indexOf("NewYork");
if (index != -1)
{ ga('send', 'event', 'yesNewYork', 'foundnewyork'); } </script>
Does anybody know how to do this?
Possibly a jQuery solution?
Your approach is correct in principle, but can be improved upon.
You are already using jQuery syntax so I just assume jQuery is available.
First I would suggest you follow Lars Graubner suggestion and select a more specific element and grab the text content instead of the html (as the name suggests the text()-function does not return HTML markup but text only).
$('.city').text()
will adress the span from your example - the dot in the selector says "Look for elements with a classname of".
This will actually return all elements that have the class, but for your use case that does not matter much.
However you must make sure that the text is actually rendered on the page before you call your jQuery selector; if you place it in the head of the page the text isn't there yet when the event tracking runs and thus your selector will return nothing.
You can either put the script in the footer of the page, or you can wrap it into jQuery's document.ready-call. This makes sure that the function only runs after the DOM of the document has rendered (meaning that the page structure is complete, event if images and other assets are not yet loaded. Text will be present at this point). So this would look like this:
$( document ).ready(function() {
var myString = $('.city').text();
if(myString.indexof('NewYork') > -1) {
ga('send', 'event', 'yesNewYork', 'foundnewyork');
}
});
(Obviously this assumes you have jQuery included).
If this still doesn't work you need to be more specific as to the actual error your are getting.

What is the simplest way to filter the content of a web page from a drop down menu?

I would like to be able to allow a user to "filter" the contents of an HTML page from a drop down menu.
I have minimal coding skills but maintain a simple website produced using Emacs org-mode. (easy to assemble pages and produce different versions of the same content using tags.) The output is simple HTML.
I can easily produce different versions of a page and make them selectable with a drop down menu to move between them, but this means I have different versions of the same content on my website, which makes retrieval from search engines confusing.
Ideally, I would like user A to be able to select to see the whole page, user B to see some of it, and user C to see most of it except a small portion. This is a convenience to the users (not for security, etc.)
What is the simplest way of implementing this? I realize a web developer would probably use Ajax, etc., but that's not me.
Sounds like you could make use of showing/hiding sections of the page with some DIVs based on a drop down SELECT.
To do this, you wrap the content that you want to filter in some DIVs and create a JavaScript function that "filters" the displayed content based on the value attribute of the SELECT.
Here is a simple example:
HTML
<select id="myDropdown" onchange="filterContent();">
<option value="A">All content</option>
<option value="B">Some content</option>
<option value="C">Little content</option>
</select>
<div id="contentA">
** Content A ***
</div>
<div id="contentB">
** Content B ***
</div>
<div id="contentC">
** Content C ***
</div>
JavaScript
function filterContent() {
var user = document.getElementById("myDropdown").value;
var contentA = document.getElementById("contentA");
var contentB = document.getElementById("contentB");
var contentC = document.getElementById("contentC");
if(user=="A") {
contentA.style.display="block";
contentB.style.display="block";
contentC.style.display="block";
} else if (user=="B") {
contentA.style.display="none";
contentB.style.display="block";
contentC.style.display="block";
} else if (user=="C") {
contentA.style.display="none";
contentB.style.display="none";
contentC.style.display="block";
}
}
Try it here: http://jsfiddle.net/JsZ8S/
Here is another example with multiple different sections that can be shown or hidden based on the selection. Note that the scheme used for IDs is contentA1, contentA2, etc. the letter being the user and the number after the letter is the sequence since IDs must be unique. Also note the difference in the JavaScript code - because we have more sections, we have to account for showing and hiding them in the if/else block: http://jsfiddle.net/JsZ8S/2/
In case you are ready to use jQuery another example is using classes. If you find that you are creating numerous sections and are tired of keeping track of IDs, you might want to use classes. Classes in this case, work like IDs that you can use again and again. You mark any section you want displayed to all users (user A) with class="contentA", any area for users A and B with class="contentB" and everything else just leave unmarked. This is starting to get a bit un-simple at this point but see what you think.
Here is an example (requires jQuery) using classes: http://jsfiddle.net/JsZ8S/5/
You cannot do it with HTML alone. HTML defines a static document with static formatting. You need at least a little bit of JavaScript to dynamically change the page. Otherwise you have to create some sort of link or button that takes the browser to a new page with the desired changes. (This is about how the web worked for the first 5 or so years.)
A small about of JavaScript plus a library like jQuery should make this easy enough to do if you have any programming experience.
HTML is used to just creating the markup and CSS is used to style it. There is no way you can do "filtering" in plain HTML. You will definitely need some JavaScript knowledge. Try your hands on jQuery and angularJS. They are really easy to learn and the documentation is pretty amazing.

Get div from page

I've looked everywhere for a technique, but I failed to find much that suited my needs.
Basically, I would like to utilize JavaScript or jQuery (probably using Ajax) to grab a div that contains a word from a page on my site.
I'm not asking anyone to code this for me, I would just like to be pointed in the right direction.
For example, let's say I have this HTML page:
<div class='findfromthis'>hello guys</div>
<div class='findfromthis'>goodbye guys</div>
<div class='findfromthis'>goodbye people</div>
I would like to display all the divs that contain the word "guys" in them.
Thank you so much in advance!!
JQuery has a contains selector that will find all elements containing specific text. Something along the lines of $("div:contains('guys')") should do the trick. Then you can use .each or .show etc to work with the selected elements.
See http://api.jquery.com/contains-selector/ for more detail.
EDIT :
The following code was deemed useful by the OP. It'll select all divs with class "findfromthis" which don't contain the phrase "guys", and remove them from the DOM:
$("div.findfromthis:not(:contains('guys'))").remove();
Give your div a class, say '.myDiv' and then via jQuery:
$('.myDiv').doSomething...
I'm not entirely sure how AJAX would play into this, but to point you in the right direction:
http://api.jquery.com/jQuery.ajax/
Your edit is an entirely different question. But you'd do the same to get the divs. In this case, you'd use 'each':
$('.findfromthis').each(function(){
// for each div you can now grab the text it contains:
DivText = $(this).text();
// now you could use a variety of different JS seach techniques to find
// your content. But one example to search for a word or word fragment would be:
if (DivText.indexOf("guys") !== -1)){
// then this div has the word 'guys' in its text somewhere
}
})
If the search term is more complex (like not wanting to find fragments) then you may want to use REGEX for the search part instead.
Again, though, not sure where AJAX would fit into this. This all can happen client-side.

Assign links and classes in JavaScript

I have a site that is in English and Spanish, and in each page of the site there is a link that leads to the Spanish version of that specific page, so if the user were on the "home.php" page, it would look like this:
<div id="language">
<ul class="language">
<li class="english"></li>
<li class="divider"></li>
<li class="spanish"></li>
</ul>
</div>
What I would like to do is leave the href and the class in the <a> tags in the HTML blank and assign a class and an href URL to the <a> depending on the page the user is on, that way I could, for example, just add that language div to an external file, and use an <include> to attach it to each page. To accomplish this I'm using the following code:
$('ul.menubar a').each(function(){
if(location.href.match('home.php')){
$('ul.language li.english a').addClass('active');
$('ul.language li.english a').append(function() {
$(this).attr('onclick', 'return false;');
});
$('ul.language li.spanish a').addClass('notactive');
$('ul.language a[href!="home.php"]').append(function() {
$(this).attr('href', 'inicio.php');
});
}
}
The problem is that the English version of the site has 4 links in the navigation bar (home.php, services.php, aboutus.php, contact.php), and the Spanish version likewise (with the corresponding translation of the URL names). I think that having to repeat that code 8 times (1 for each link, 4 links in each language) would be excessive and would actually add more code than simply adding the class and href url in the HTML. The point of using JS would be to simplify things.
So I basically would like to know if anyone can think of a better way to do this, that wouldn't require that much code. I'm trying to avoid having to, in the event that I'd need to change something, have to edit each different page. Also, I would like to know if this is the best way to achieve want I want to do using JavaScript.
HTML is best suited for managing content. CSS is best suited for presenting that content, and JavaScript is best suited for determining how that content behaves. Instead of trying to inject links and control the HTML from JavaScript; instead, leave the content where it belongs, inside the HTML, and use JavaScript to define one or two event-handlers to take action based on the class values on the hyperlinks themselves.
You already have a class on your English hyperlinks, and a separate class on your Spanish hyperlinks, so you can use this to your advantage.
Writing the Click Handlers:
Since toggling your "Language switch" most likely causes a boolean value to be set, you can use two click handlers to target all of your English links and all of your Spanish links, and then control the behavior based on the value of that switch at the time the links are clicked.
// handler for all English links
$('li.english a').click(function(event) {
event.preventDefault();
if(/* Switch is english */) {
window.location = $(this).attr("href");
}
});
// handler for all Spanish links
$('li.spanish a').click(function() {
event.preventDefault();
if(/* Switch is SPANISH */) {
window.location = $(this).attr("href");
}
});
Note that when a link is clicked, we first check the switch. Depending on it's value, we either redirect to that hyperlink, or simply prevent the default behavior -- going to a new page -- from completing.
Handling the Presentation:
Now, your other problem is going to be that, assuming your Spanish site and your English site are one in the same, you'll now see 8 hyperlinks in total. Again, this is where your switch can come in handy.
// single handedly hide or display the relevant content, based on the switch
function switchToEnglish() {
$('.english').show();
$('.spanish').hide();
}
function switchToSpanish() {
$('.spanish').show();
$('.english').hide();
}
Now, I don't know what else is contained in your switch function, but the general idea here is that we don't need to modify the content. We just need to show and hide the content. You'd need to integrate this concept into your existing switch function, if you don't already have something like this in place.
There are several advantages in this approach:
Your Web designers will still see href's in the HTML and can read and understand the HTML without needing your help or needing to go and look at JavaScript code. Not only will they see familiar patterns that they're used to seeing, but you'll likely have a better working relationship with them.
Search engines spidering your site will be able to read the links and follow them.
Browsers without JavaScript will be able to process the links. Some people seem to care about this. I don't. But it's worth mentioning anyway.
In summary, you're right about it being easier to manage in HTML. By using this technique, you can eliminate the repetition in the code that you're rightfully concerned about, and also move the content back to the HTML, as your gut is telling you is the correct thing to do. Not only will your code be more readable, but you'll get better SEO results as well.

How to use onmouseover?

I have a list being displayed on a JSP. On mouse hover on any of the value i need to show a description corresponding that value. Need to show description not as an alert and also cannot make the values as hyperlink.
eg.
suppose the value is ABC so on mouse hover should show AppleBoyCat.
need to use onmouseover. let me know how to do it..
What do you want to do? If you just want to show a tooltip, you can set the title attribute of any element and it will be displayed as a tooltip.
Also, the abbr tag can be used as tooltips too:
<abbr title="test">stuff</abbr>
You can go about it in two ways:
1 - a hidden dom object (a div for instance) which reveals itself when you roll over whatever
or
2 - you can rewrite the html of the particular element you're mousing over.
You can load this data in when you load everything else (either as Javascript objects, or as markup, though that's much bulkier) or you can asynchronously load the description data from a service when you mouse over (though you'll have more lag).
jQuery is a quick and dirty way to achieve this (more quick than dirty), but straight JS or pretty much any other JS library will do as well.
Perhaps not the cleanest solution but something like this:
<a class='hover' rel='tooltip'>Link</a>
//Some hidden div, putting css inline just for example
<div id='tooltip' style='display:none;'>Content</div>
$(function() {
$('.hover').mouseover(function() {
var tooltip = $(this).attr('rel');
$('#' + tooltip).fadeIn();
});
});
And offcourse add a callback hiding it again. It just takes the value from rel of the link and use as an id for the div to show.
This is a quick and dirty solution, can be made alot smoother if you just work with it a little;)
There also alot of plugins out there allowing the same functionality in a cleaner fashion.
*Edit: Just noticed you added a comment on another post that you can't use jQuery.. shouldn't tag a post with something you're not intending to use.
As TJHeuvel already said, you can simply use the title attribute.
Best approach is to build the list with both the value and title attribute from within JSP, if not possible for some reason, you can build client side array of each value and its corresponding description then using JavaScript dynamically assign the title on mouseover.
Show us some more code to get more/better help.
For simple tooltips, the title attribute is most effective, as pointed out by TJHeuvel
If you need more advanced tooltips with HTML and CSS formatting, I'd suggest you use an external library.
One that works nicely without jQuery ist wz_tooltip download here, documentation here
When included correctly, you can add tooltips by calling the functions Tip() and UnTip() as follows:
Homepage

Categories

Resources