Checking to see if page title is in array via jQuery - javascript

I've created semi-dynamic page titles on a static site by using the following on each page (for example):
<?php $title="Example"; ?>
And added this to my header file:
<title>Company Name Here<?php if ($title!="") { echo " | $title"; } ?></title>
That part is working well.
Now, I would like to use jQuery to check if a page title for the ACTIVE page is in an array so that (if it is) I can apply a class to a navigation element or two. And, if it not in the array, I'd remove that class. Like so (in partial pseudocode):
if $(title) of currently visible page is in this array(about, page2, page3) {
$('a#idname').addClass('selected')
} else {
$('a#idname').removeClass('selected')
}
Maybe there's a better way to do this. I'm open to suggestion. I'm just not very clear on the syntax for determining:
What page is currently loaded
How to use some identifier for the current page to change the class of an element on the page after page load. I know how to do it on click, but as soon as the page loads, the class goes away.
Any help greatly appreciated. Thanks in advance!

You can retrieve the document's title by accessing the title property on the document object, document.title. In order to get the portion of the string after the pipe, |, you could simply split the title on the | character and then get the second element in the returned array.
If the page's title is "Company Name Here | About" like in your question, then document.title.split('|') would return the array ["Company Name Here ", " About"], therefore .split('|')[1] would return the string "About".
Use the .indexOf() method in order to check if the title string is in the array titleArray and then add/remove the class accordingly.
Here is a basic example:
var title = document.title.split('|')[1];
var titleArray = ['About', 'Page2', 'Page3'];
if (title && titleArray.indexOf(title.trim()) > -1) {
$('span').addClass('selected');
} else {
$('span').removeClass('selected');
}
.selected { color: #f00; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<title>Company Name Here | About</title>
<span>The title is in the array if this is red.</span>

Related

Target closest class if string contains value

I have a localstorage item that gets stored in the page head, the const for this is also in the page head so that it gets loaded once, the below code duplicates for all product card items that load onto the category page, this code is added inline in script tags into the product card include, so that the metafield can collect each products unique metafield value, to make the example simpler I've just put "hello" where the metafield would be.
What I'm trying to do is check if "string" includes the value "hello", and if it does the script should find the closest class called "container" and add html on to the end of it.
In < head > tag:
const string = 'hello my name is';
In product card include:
window.onload = function() {
if (string.includes("hello")) {
$(target).closest('.container').after('<div class="pass">some message</div>');
}
}
I haven't found any errors in the code but I'm sure there's something obvious to someone who has more experience, would be great if anyone can help out!
Here is my latest attempt to fix the issue, still nothing is being added in html..
<script>
window.onload = function() {
const string = 'hello my name is';
const div = document.getElementById('6204142256316');
if (string.includes("hello")) {
div.insertAdjacentHTML('afterbegin', '<div class="pass">some message</div>');
}
}
</script>
<div id="6204142256316"></div>
Have the target be some selector the uniquely identifies the script element that each “product card” contains. For example, each script element inside of the “product card” could have an id of product-card-script-${PRODUCT_ID}.
The function set to window.onload does not necessarily know that it is in the context of the product card when loaded.
This answer assumes that you have control of adding an id attribute to each script added to each product card.
The solution was to make any liquid render outside the script - so this now works
<script>
window.onload = function() {
const string = 'hello my name is';
const div = document.getElementById('6204142256316');
if (string.includes("hello")) {
div.insertAdjacentHTML('afterbegin', '<div class="pass">some message</div>');
}
}
</script>
<div id="6204142256316"></div>
To show what I was doing wrong:
{{ product.id }}.insertAdjacentHTML.......
Even though liquid is rendered prior to JS it seems this should always be like the below:
const div = document.getElementById('{{ product.id }}');
div.insertAdjacentHTML...........
Once I did that it worked perfectly.

Changin unwanted HTML from plugin generated code

I'm using the WP plugin Really Simple Breadcrumbs and it generates these links for me:
<div class="breadcrumb">
Example 1
" >> "
Example 2
" >> Blog Page Title Lorem"
</div>
I need to change two things in this html. One, I need to rewrite the first link to say Blog . Second, I need the trailer "Blog Page Title Lorem" to be deleted. Third, I'd like to change the >> to >. I think all of these would use the same technique so Im listing them all in the same question. I'm open to JS, jQuery, CSS display/hide tricks, whatever works. How do I do this?
If you go into the plugin folder you will find breadcrumb.php
In that file there will be a variable called $seperator that has its value set to >> and you should be able to alter it there.
If you want to change any the CSS for for the <a> just use .breadcrumb a in your style.css file.
As for changing the content titles, those are generated by the plugin via the information in your database ( titles, slugs, permalinks etc etc ). The first link SHOULD take your blog title as its paramater. If it's not, before the loop starts in breadcrumb.php you could also write that in before so that it's always generated.
Blog page lorem being the last in the crumbs should be assigned to whatever page you have. If you can find the spot in breadcrumb.php that generates that, you could delete it and put this in there:
the_title();
Best of Luck.
To get the next text-node after element, Use nextSibling.nodeValue. The Node.nextSibling read-only property returns the node immediately following the specified one in its parent's childNodes list, or null if the specified node is the last node in that list.
The Node.nodeValue property returns or sets the value of the current node.
To set the href of the first element, index which is first argument in each could be used.
Try this:
$('a').each(function(index, item) {
if (index === 0) {
item.href = '/blog';
}
item.nextSibling.nodeValue = ' > '
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="breadcrumb">
Example 1 " >> "
Example 2 " >> Blog Page Title Lorem"
</div>
Fiddle here
//
//find first child and change href
document.getElementsByClassName('breadcrumb')[0].children[0].href='"/blog"';
//find first child and change innercontent
document.getElementsByClassName('breadcrumb')[0].children[0].innerHTML='Blog';
//find all nodes in breadcrumb
var all_nodes=document.getElementsByClassName('breadcrumb')[0].childNodes;
//loop through to find pattern
for(var i=0;i<all_nodes.length;++i){
//replace any pattern with Blog.....and replace it with nothing
all_nodes[i].textContent=all_nodes[i].textContent.replace(/ *Blog Page Title Lorem */,'');
//replace all >> with >
all_nodes[i].textContent=all_nodes[i].textContent.replace(/ *>> */,'>');
}
<div class="breadcrumb">
Example 1
" >> "
Example 2
" >> Blog Page Title Lorem"
</div>

How do I give an ID to part of the contents of a <title> tag?

I have a title tag that looks something like this:
<title>My Page Title - Photo #3</title>
I want to use JavaScript to change the numeric part of it, without having to hard code the "My Page Title - Photo #" string which is generated server side.
I tried wrapping the number in a span so that I could change the contents of the span:
<title>My Page Title - Photo #<span class="photoid">3</span></title>
But it seems HTML is not allowed in the title tag. I'd really like to pursue the class approach if possible as that would allow me to use a line of jquery such as this:
$('.photoid').html(new_photoid);
Did I mention that the photoid appears in several places on the page, which is why I want to be able to use this oneliner to change them all at the same time? For example:
<p>A paragraph also containing the number <span class="photoid">3</span></p>
A title can only have text, so you need to parse it out.
document.title = document.title.replace(/\d+$/, "new value");
title can't be set like that,
it's not a child of .html
some thing like
var num = 3;
document.title = "foo "+num
to set the title, then reuse num for these photoids.
Use the jQuery onDocumentReady syntax:
$(function () {
var elements = $('.contains_photoid');
elements.html(elements.html().replace("3", "4"));
$(document).attr('title', $(document).attr('title').replace("3", "4"));
});
You can't see the title change in this example, but that is the syntax. See Changing the page title with Jquery
The "3" and "4" can be changed to anything, so you can create the page with a unique character string in place of the real ID in order to easily replace it if it appears in text with numbers already in it.
http://jsfiddle.net/ZmXj5/1/
Javascript
var photoID = 355; //this assumes you have some code where you set this photoID value
var title = document.title;
title = title.substr(0,title.lastIndexOf('#')+1);
document.title = title+photoID;
See this fiddle for proof: http://jsfiddle.net/xrkhA/
(I used a div content because you can't use title in jsfiddle)
You can either use, but $('title') will fail in IE8
document.title="new title";
or
$('title').html('new title');
or
$(document).attr('title','new title');

How would I make a self-linking <div>?

After much Googling, I resort to the chance at ridicule and moderation on Stack Exchange.
What I am trying to do sounds simple enough. I want to make a <div> id/class that will link automatically create a link to itself via some kind of scripting.
Let me put down some pseudocode, before I make it sound more complicated than it is:
#Let div.link = xxx.html
#Let div.pic = xxx.png/jpg
for div in HTMLdocument:
if div.class == "autolink":
div = "<img src=\"mysite/" + div.pic + ">"
Now, obviously that's Python pseudocode, but I am familiar(ish) with PHP and Javascript. Basically, I want to make the div generate an HTML link without having to actually type out the tags and links for every given div on a web page. I want to be able to type, in my index.html:
<html>
<head></head>
<body>
<div class = "1"></div>
<div class = "2"></div>
</body>
</html>
and then to be presented with a page that has the two divs linked, imaged, and, preferably, formatted.
Like I said, the problem seems simple, but I can't seem to get it to work right, in any language. This seems like a thing that would be very useful for begiiner web designers.
PERSONAL NOTE:
I would preferably like to see a solution in PHP or Javascript, but if you are good with Django and want to show me how to get it done in that, I would be just as grateful!
=========================================
EXAMPLE:
Let's say you have a browser based RPG, and you want to show your player's inventory. The Inventory page would display the items in a players inventory, complete with a link and image, based on whatever was in that user's inventory page. It would look like this (this is VERY rough output, Statements tagged in #these# are not code, and should be interpereted as what they describe):
<h1>User's Inventory:</h1>
<p><div class = "item_1">#Link to page of 'item_1', image of 'item_1'#</div></p>
<p><div class = "item_2">#Link to page of 'item_2', image of 'item_2'#</div></p>
The above would display, roughly, a header that said "User's Inventory", and then display a linked image of item_1, followed by a newline and then a linked image of item_2, where said items would be in a separate file OR a list that lists all the items and their respective links and images.
You can use jquery, and when page dom is loaded, you cycle through each div that has the class autolink and do your manipulations (add your desired html into each div). You can use the id of each div to place data inside. You can use a prefix to that id values for different types of data. For example, im using "inventory_" as a prefix.
<h1>User's Inventory:</h1>
<p><div class = "autolink" id="inventory_item_1">#Link to page of 'item_1', image of 'item_1'#</div></p>
<p><div class = "autolink" id="inventory_item_1">#Link to page of 'item_2', image of 'item_2'#</div></p>
then jquery on document ready:
<script type="text/javascript">
$(document).ready(function ()
{
// define your website here
var mysite = "http://www.example.com/";
// this will cycle through each div with class autolink. using `this` to reffer to each.
$(".autolink").each(function () {
// we get for div with id="inventory_item_1" ...
var mylink = $(this).attr('id').replace("inventory_",""); // ... a value item_1
var myimagesrc = $(this).attr('id').replace("inventory_","image_"); // ... image_item_1
$(this).html('<img src="'+mysite+'images/'+myimagesrc+'.jpg">');
// the above will add html code of this format:
// <img src="http://www.example.com/images/image_item_1.jpg">
});
});
</script>
try it here:
http://jsfiddle.net/5APhT/2/
I'll give a sample in php. Here is an example if you already have a set of links to use
<?php
//Create a multidimensional array to store all you need to create links
$links['1'][]="http://www.yahoo.com";
$links['1'][]="yahoo.com";
$links['2'][]="http://www.facebook.com";
$links['2'][]="yahoo.com";
$links['3'][]="http://www.google.com";
$links['3'][]="yahoo.com";
foreach($links as $class => $innerArray){
$link=innerArray[0];
$linktext=innerArray[1];
echo "<div class='$class'><a href='$link'>$linktext</a></div>";
}
?>
This creates the divs for you so you don't have to add them in advance.
You can add images in the same manner

Javascript add ID and hash link to new ID

I "learned" JavaScript a few months ago but quickly picked up Python and spent the past few months writing programs in that language, so I decided it would be a good idea to go back and actually learn JavaScript. Right now I'm making a very simple "blog" with JS that takes the title of the post, generates a hash link from the post, and creates a recent posts section where you can click the link to jump to the post in the page.
For instance, say one of the posts is formatted like this:
<h2 class="post">Another post for you</h2>
<h4>I know you love these</h4>
With multiple posts, and an empty container at the bottom, which will be used to append the recent posts links:
<div id="get-post"></div>
My JS code basically grabs each title with the post class and creates a hash link from the element's title (removing spaces and commas). It then creates and appends a text node consisting of the post title, and then appends the entire link into the get-post container.
var postList = $('#get-post');
var post = $('.post');
function generateRecentPosts() {
post.each(function() {
// Create link from post title that will be used to
// access that post.
var postLink = document.createElement('a');
// Create text node from post title that will be appended
// to the postLink.
var text = document.createTextNode($(this).html());
// Add elements to the DOM.
postLink.href = createLocalLink($(this));
postLink.appendChild(text);
postList.append(postLink);
postList.append('<br />');
});
}
function createLocalLink(elm) {
// Creates the href link that will be used to go to a blog post.
// For example, if the title of the elm parameter is "My Post",
// a link is created called #My-Post that will be used to access
// that post.
elm.id = elm.html().replace(/,/g, '').replace(/\s/g, '-');
console.log(elm.id); // Make sure the ID is added.
return '#' + elm.id;
}
generateRecentPosts();
My problem is that the links it generates to not point to the ID created for each title. When I click on the link, I can see that it successfully created the href hash #My-Post and added it to the anchor tag, but it doesn't take me to the post title.
Example: http://jsfiddle.net/samrap/GQtxL/
I even added a console log function to make sure the ID is being added to the title as I thought that was the problem, but it isn't because the console is printing the correct new ID. I could really use some help in figuring out where exactly the problem is here.
Your h2 tags need to have an id or name attribute that corresponds with the link, that is what makes internal links work. The id is not getting added because you are accessing a jQuery object as if it were a DOM node (elm.id = ...). Modify your createLocalLink function to use jQuery's attr method to set the id property:
elm.attr('id', elm.html().replace(/,/g, '').replace(/\s/g, '-'));
Additionally, since you have jQuery available you could whittle your code down to:
var $this = $(this),
link = createLocalLink($this);
var $postLink = $('a', {
text: $this.text(),
href: link
})
postList.append($postLink).append('<br />');
Here is your fiddle updated: http://jsfiddle.net/GQtxL/1/
This is because your link uses the href = "#My-Post" but none of the posts has the ID "My-Post". It only has a class "post".
This happens because the argument that your are passing to the createLocalLink() function is a DOM Node. But by doing elm.id you are not changing the DOM property but adding another property to the "elm" object. Thus your "elm" object is
x.fn.x.init[1]
0: h2.post
context: h2.post
id: "Another-post-for-you"
length: 1
__proto__: Object[0]
Thus the actual post never gets the attribute ID only "elm" object gets it. Note the empty ID attribute below
draggable: false
firstChild: text
firstElementChild: null
hidden: false
id: ""
innerHTML: "Another post for you"
innerText: "Another post for you"
Thus your document has no element with the ID "My-Post". You can view the source of your HTML to verify this.
For internal links to work there should be an element with the same ID as that used in the href attribute of the link.
For example
<div id="post1">
Your Post Here
</div>
<!--just to show the effect of moving to the post-->
<div style="clear:both; height:900px"></div>
Click Here
This would work because there is an element with the id "post1" and the link uses the href "#post1" which links it to the corresponding element. Hence, add the corresponding id to your post as well (other than your link) for it to work.
In function createLocalLink you are using elm argument as dom node, but actually passing a jQuery wrapped object to it, which don't have id property. To get it work, use elm.get(0).id = ... or elm.attr('id', elm.text().replace(/,/g, '').replace(/\s/g, '-'););

Categories