Javascript, if URL then item - javascript

As the title suggests I am looking for a script command for "if url", then "item." I am working on a wordpress theme that I am translating. All of the content has been translated except for 1 item that is essentially a tile menu item.
I figure the best/only way to translate it since the theme does not support multilungual sites is to give it a javascript condition.
Perhaps I am wrong in my approach but I have been trying something like the following:
if(window.location.pathname == "example.com")
{
<li class="b1">
<a href="http://example.com/?page_id=69">
<h5>Example</h5>
<span>Thank you!.</span>
</a>
</li>
}
else
{
<li class="b1">
<a href="http://example.com/?page_id=69">
<h5>Example</h5>
<span>Merci beaucoup!.</span>
</a>
</li>
If anyone could tell me what im doing wrong that would be pretty cool
Thanks

You can't embed HTML into the middle of your javascript like that - everything in a script has to be actual javscript. You can use javascript to insert HTML into the DOM, either at the current position or in other positions in the document. For example, you could do this in your HTML:
<li class="b1">
<a href="http://example.com/?page_id=69">
<h5>Example</h5>
<span><script>
if(window.location.hostname == "example.com") {
document.write("Thank you!.")
} else {
document.write("Merci beaucoup!.")
}
</script></span>
</a>
</li>
You will also have to fix your javascript logic because location.pathname does not contain the domain - perhaps you meant to use .hostname instead.

your if statement is wrong because you are checking your domain against the path.
you should replace
window.location.pathname
with
window.location.hostname
put the javascript only where you need the text replaced: no need to write all the html twice.
if(window.location.hostname == "example.com") {
document.write("Thank you!.")
} else {
document.write("Merci beaucoup!.")
}

Something like this works.
<ul>
<li class="b1"> </li>
</ul>
<script language="javascript">
if(window.location.hostname == "example.com") {
document.querySelector('.b1').innerHTML = "<a href='http://example.com/?page_id=69'><h5>Example</h5><span>Thank you!.</span></a>";
}
else
{
document.querySelector('.b1').innerHTML = "<a href='http://example.com/?page_id=69'><h5>Example</h5><span>Merci beaucoup!.</span></a>";
}

You maybe should use a regular expression to catch the url, did you already tried?
<li class="b1">
<a href="http://example.com/?page_id=69">
<h5>Example</h5>
<span><script>
var expression = /[-a-zA-Z0-9#:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9#:%_\+.~#?&//=]*)?/gi;
var regex = new RegExp(expression);
if (window.location.hostname.match(regex) ){
<span>Thank you!.</span>
}
else{
<span>Merci beaucoup!.</span>
}
</script></span>
</a>
</li>

Related

Replace in variable a href address

I am beginner web developer.
I have small problem with my code:
var nodes = document.querySelectorAll('.breadcrumb-item');
if(nodes != undefined && nodes !=''){
var first = nodes[0];
console.log('xxxxxx' , first);
}
It's return me:
[Log] xxxxxx
<li role="presentation" class="breadcrumb-item">
Home
</li>
I need check:
if a href is "Home" then replace href from "#/" to "/dashboard"
if a href is not "Home" then show console.log('not find').
How can I make it?
I have dynamic string. For example:
<li role="presentation" class="breadcrumb-item">
Home
</li>
<li role="presentation" class="breadcrumb-item">
Dogs
</li>
<li role="presentation" class="breadcrumb-item">
calls
</li>
<li role="presentation" class="breadcrumb-item">
cats
</li>
I need replace URL ONLY for Home
I've written assuming that Home will always be first in order. If you're going to change its order, you'll will have to change the index for nodes inside if block.
const nodes = document.querySelectorAll(".breadcrumb-item");
if (nodes.length > 0) {
const first = nodes[0].firstElementChild;
first.href = "/dashboard";
console.log(first);
}
Previous answer is correct. Maybe the following gives you a clearer understanding:
const nodes = document.querySelectorAll('.breadcrumb-item');
if (nodes.length > 0) {
const first = nodes[0].firstElementChild;
let currentUrlTitle = first.text.trim().toLowerCase();
if (currentUrlTitle == 'home') {
console.log(first.text);
first.href = '/dashboard';
console.log(first.href);
} else {
console.log(currentUrlTitle);
}
}

Angular.js nesting curly braces in ng-bind-html

I am making a spelling app using JavaScript and Angular.js. When the user has spelled their word correctly, the view should say "Word already completed!", and when the user has not yet completed their word, the view should display a list of friends.
Therefore, I need to change the innerHTML of the object from within my JS script (so that it updates when the user spells their word correctly).
This is the if statement that I use to decide between the two innerHTMLs:
if(wordCompletedVar) {
$scope.friendsHTML = "<li><a> Word already completed! </a></li>";
} else {
$scope.friendsHTML = "<li class='user-display' style='padding: 15px' ng-repeat='friend in friendNames track by $index'><img src='{{profilePicture($index)}}' class='img-circle user-display-img'><div class='user-display-name'><a href = '#/trade/{{getFriendUsername($index)}}' ng-click='playSound('whoosh')' style = 'color: white'>{{friend}}</a></div></li>";
}
In my HTML doc, I am trying to inject friendsHTML using ng-bind-html:
<ul class="dropdown-menu" id="friendsDropdown" ng-bind-html = "to_trusted(friendsHTML)"></ul>
It works with the simple sentence, but with the more complicated HTML (with nested Angular.js curly brackets {{}}), the brackets display instead of the angular object (i.e. {{friends}}). The same happened when I used ng-bind-html without the to_trusted function.
This is a clearer view of the HTML I am trying (and failing) to inject:
<li class='user-display' style='padding: 15px' ng-repeat='friend in friendNames track by $index'>
<img src='{{profilePicture($index)}}' class='img-circle user-display-img'>
<div class='user-display-name'>
<a href = '#/trade/{{getFriendUsername($index)}}' ng-click='playSound('whoosh')' style = 'color: white'>{{friend}}</a>
</div>
</li>
The to_trusted function that I am using is:
$scope.to_trusted = function(html_code) {
return $sce.trustAsHtml(html_code);
};
(and I do include $sce in my controller).
How can I nest the curly-bracket angular notation within the ng-bind-html injection? I have found a lot of documentation on either the curly brackets or ng-bind-html, but I haven't seen anything on how to use them together (or how to accomplish what I am trying to accomplish in a different way-I am open to suggestions!)
The best way to handle this would be to avoid injecting HTML at all, and instead use a conditional statement like ng-if or ng-show.
something like the following:
<li ng-if="wordCompletedVar"><a> Word already completed! </a></li>
<li ng-if="!wordCompletedVar" class='user-display' style='padding: 15px' ng-repeat='friend in friendNames track by $index'>
<img src='{{profilePicture($index)}}' class='img-circle user-display-img'>
<div class='user-display-name'>
<a href = '#/trade/{{getFriendUsername($index)}}' ng-click='playSound('whoosh')' style = 'color: white'>{{friend}}</a>
</div>
</li>
An alternative would be along the lines of making a directive as below. You can modify parameters if you want reuse etc -
app.directive('userDisplay', ['$compile',function ($compile) {
return {
template : '<input/>',
link: function(scope, element, attrs) {
scope.$watch('wordCompletedVar',function(){
var html;
if(scope.wordCompletedVar) {
html = "<li><a> Word already completed! </a></li>";
} else {
html= "<li class='user-display' style='padding: 15px' ng-repeat='friend in friendNames track by $index'><img class='img-circle user-display-img'><div class='user-display-name'><a href = '#/trade/{{getFriendUsername($index)}}' ng-click='playSound(\"whoosh\")' style = 'color: white'>{{friend}}</a></div></li>"
}
element.html(html);
$compile(element.contents())(scope);
});
}
};
}]);

How to sort html content (sort by author, sort by date etc) using Javascript

I recently started learning javascript so i dont know much yet which is why i needed a some help and guidance.. , I want to make a list of images with links on a page which can be sorted in the order I want after clicking on "sort by author" or "sort by date" for example.. I tried to make something :
Javascript:
var wspeare = document.getElementsByClassName("willimshakespeare");
var jgreen = document.getElementsByClassName("johngreen");
function Sortbyauthor(author) {
this.author = author;
if (author === "williamshakespeare") {
for(i=0; i<wspeare.length; i++) {wspeare[i].style.display="block";}
for(i=0; i<jgreen.length; i++) {jgreen[i].style.display="none";}
};
else if (author === "johngreen") {
for(i=0; i<wspeare.length; i++) {wspeare[i].style.display="none";}
for(i=0; i<jgreen.length; i++) {jgreen[i].style.display="block";}
};
HTML:
<li class="williamshakespeare">
<img src="example"/>
</li>
<li class="johngreen">
<img src="example"/>
</li>
So when i did something like Sortbyauthor("johngreen") it worked but when the number of authors gets to 8-9 with 10-12 books the amount of code gets very repetitive and long plus the alignment of images gets weird.
So if anyone could guide me on how to make a sorting program that would be very helpful. After getting some practice with how DOM works I am planning to learn jQuery so if jQuery is needed for things like sorting then ill wait till I learn that.
Sorry if i posted this in the wrong forum or something its my first post...
Click run code snippet, then click sort
function doSort() {
//grab all the lis
var lis=document.getElementsByTagName('li');
//make an array to place each author into
var authors=[];
//go through each li
for (i=0;i<lis.length;i++) {
//put the author in the array
console.log(lis[i]);
authors.push(lis[i].getAttribute('class'));
}
//sort
authors.sort();
//get the ul
var ul=document.getElementById('authors');
for (i=0;i<authors.length;i++) {
console.log(authors[i]);
//grab each author in the array
li=document.getElementsByClassName(authors[i])[0];
//add it back, sorted
ul.appendChild(li);
}
}
<input type=button onclick=doSort(); value='click to sort' />
<ul id=authors>
<li class="williamshakespeare">william shakespeare
<img src="example"/>
</li>
<li class="johngreen">john green
<img src="example"/>
</li>
<li class="henrymiller">henry miller
<img src="example"/>
</li>
<li class="stephenking">stephen king
<img src="example"/>
</li>
<ul>

How to change href value using javascript or jquery?

<div class="container-fluid">
<img class="pull-left" onclick="MarkPopup()" style="width:50px;height:50px" src="/assets/mark.jpg">
<ul class="nav pull-right">
<li>
<li>
Contact Club
</li>
<li>
<li class="dropdown">
</ul>
</div>
I want to change the href value "/ContactClub" to "somethingelse". How is this done please?
Two ways ;)
jQuery style:
// Select a with href attribute = /ContactClub
$('a[href="/ContactClub"]').prop('href', 'newhref...');
Pure-js solution (untested)
var elements = document.getElementsByTagName('a');
for (var i = 0; i < elements.length; i++) {
if (element[i].href === '/ContactClub') {
if (element.setAttribute !== 'function') {
element[i].href = 'newhref';
} else {
element[i].setAttribute('href', 'newhref');
}
}
}
I would add an id to the a tag:
<a id="contact_link" href="/ContactClub">Contact Club</a>
And then do either,
$('#contact_link').attr('href', 'new url');
or,
document.getElementById('contact_link').href = 'new url';
Note: You can also use the jQuery prop method in the same fashion as attr above. This is somewhat a matter of preference. As href is principally thought of as an attribute (with a corresponding, but not dynamic or disconnected js property), I would suggest using attr. Other attributes like value will depend on what you're trying to retrieve. Do a bit of research on the differences.
You can use either prop() or attr():
$('a[href="/ContactClub"]').attr('href', 'New Href here');
or:
$('a[href="/ContactClub"]').prop('href', 'New Href here');
Fiddle Demo
try
$("li a").attr("href","new value");

jquery / javascript insert ul / li elements into this html

is it possible to amend the following html into the source linked at the bottom of this page? I have limited scripting access to the source page so I'm looking for a way to change the page using jquery or js.
Also the department id's will be completely random and there will be a different number of links relative to each group, therefore it will need to be dynamic. I've tried appending but I'm having trouble as inserting starting or closing tags only, so not sure how to go about this. Thanks in advance for any help offered.
Additions I need in the code are marked with **'s
Original source:
<ul class="menu">
<a id="group-car" href="#">Car</a>
<li><a id="department-2" href="link">Black</a></li>
<li><a id="department-4" href="link">Blue</a></li>
<a id="group-bike" href="#">Bike</a>
<li><a id="department-1" href="link">BMX</a></li>
<li><a id="department-6" href="link">Racing</a></li>
<li><a id="department-12" href="link">Mountain</a></li>
</ul>
What I need to end up with:
<ul class="menu">
**<li>**
<a id="group-car" href="#">CAR</a>
**<ul class="acitem">**
<li><a id="department-2" href="link">Black</a></li>
<li><a id="department-4" href="link">Blue</a></li>
**</ul>**
**</li>**
**<li>**
<a id="group-bike" href="#">BIKE</a>
**<ul class="acitem">**
<li><a id="department-1" href="link">BMX</a></li>
<li><a id="department-6" href="link">Racing</a></li>
<li><a id="department-12" href="link">Mountain</a></li>
**</ul>**
**</li>**
</ul>
jQuery(".menu").children("a").each(function()
{
jQuery(this).nextUntil("a").add(this).wrapAll("<li></li>");
jQuery(this).nextUntil("a").wrapAll("<ul></ul>");
});
jsfiddle
Does this need some explanation?
EDIT oops! I didn't see the classes on them:
jQuery(".menu").children("a").each(function()
{
jQuery(this).nextUntil("a").add(this).wrapAll("<li></li>");
var jUL = jQuery("<ul></ul>").addClass("acitem");
jQuery(this).nextUntil("a").wrapAll(jUL);
});
jsFiddle
What a beautiful challenge!!
Here you have. Tested in FF 3.6 and works!
function fixMarkup(){
var liFamilies = [];
var iFamily = 0;
$(".menu li").each(function(){
if($(this).prev().is("a"))
liFamilies[iFamily] = [this]; //Start a family
else
liFamilies[iFamily].push(this); //Append to family
if($(this).next().is("a")) iFamily++; //A new family begins
});
//console.log(liFamilies);
for(var i = 0; i< liFamilies.length; i++){
var family = liFamilies[i];
$(family).wrapAll('<ul class="acitem" />');
var ulNew = $(family[0]).parent()[0];
var aElem = $(ulNew).prev()[0];
$([aElem, ulNew]).wrapAll("<li/>");
}
}
$(document).ready(function(){
fixMarkup();
});

Categories

Resources