dynamic breadcrumb schema - javascript

I set dynamic schema for breadcrumb in JavaScript code ,and very thing is ok. but when tested Url in the rich result test from google ,often time does not find schema for this.
when I see inspect of my page, schema existed of the script tag.
what is reason that don't working well.?
JavaScript code is this:
<script>
var bread = {
"##context": "https://www.schema.org",
"##type": "BreadcrumbList",
"itemListElement": []
}
var exist = false;
$('.breadcrumb li').each(function (index) {
var item = {}
var href = $(this).find("a").attr('href');
if (href) item["##id"] = "#Repository.Settings["WebSiteAddress"]" + href // OR location.protocol+"//"+location.host+href;
else item["##id"] = "#Repository.Settings["WebSiteAddress"]" + window.location.pathname
item["name"] = $.trim($(this).text());
bread.itemListElement.push({
"##type": "ListItem",
"position": index + 1,
item
})
exist = true;
});
if(exist){
var jsonStrb = JSON.stringify(bread);
var s2 = document.createElement("script");
s2.type = "application/ld+json";
s2.id = "BreadcrumbJson";
$("body").append(s2);
$('#BreadcrumbJson').append(jsonStrb);
} </script>

It could be because the code runs before the DOM is ready, so the RRT doesn't pick it up.
Try running it afterwards - as you're using jQuery - by wrapping your code in the .ready method:
$(document).ready(function() {
// your code
});
Also, make sure you're using a valid JSON-LD syntax. Namely, special properties should have a single "#" character (e.g. "#context", "#type"), instead of double ("##context", "##type" and so on), although the code looks fine on your screenshot/localhost, unlike the separate code snippet you've provided.

Related

jQuery add class based on parent URL

on my homepage, I currently have a jQuery that adds a class (in this case an underline) to the link element. This works great and is based on comparing the url (url/firstsubmenu) in the browser with the href of the link element.
However as soon as I go to a child of that link element (url/firstsubmenu/secondsubmenu), the class is gone. I have tried to split the url so that the jQuery always looks for the parent but I just can't solve it. Can you help me?
Could it be solved by adding another code, like maybe "if (this).children().length > 0 ?"
Here is my jQuery:
var cururl = window.location.href;
cururl = cururl.split('#')[0];
jQuery("a.rs-layer").each(function(){
if(jQuery(this).attr('href')=== cururl){
jQuery(this).addClass("current-slider-menu");
}
});
EDIT: I am new to this, and I have tried so many different codes, googled for hours. I now know that I can only write JavaScript in my CMS. That is, I cannot use jQuery operators such as, for example, $.
Try this,
Change the class/selectors as per your requirement. This will add a unique class in the li element, now you can style this using css.
$(document).ready(function() {
$(".main_menu li").removeClass('current-slider-menu');
$(".main_menu li>a").filter(function(){
return this.href == location.href.replace(/#.*/, "");
}).parent("li").addClass("current-slider-menu");
});
You're definitely on the right track.
You can grab the currentURL (before the anchor #):
const currentURL = window.location.href.split('#')[0];
Then you can split the currentURL into its constituent folders:
const currentURLArray = currentURL.split('/');
Then, separately, you can grab all the myLinks:
const myLinks = [...document.querySelectorAll('a.rs-layer')];
And finally you can cycle through myLinks and if the name of the folder you want to match does match the name of the equivalent folder in the currentURL, then you can add the .current-slider-menu class:
for (myLink of myLinks) {
if (myLink.href.split('/')[1] === currentURLArray[1]) {
myLink.classList.add('current-slider-menu');
}
}
Complete Example:
const currentURL = window.location.href.split('#')[0];
const currentURLArray = currentURL.split('/');
const myLinks = [...document.querySelectorAll('a.rs-layer')];
for (myLink of myLinks) {
if (myLink.href.split('/')[1] === currentURLArray[1]) {
myLink.classList.add('current-slider-menu');
}
}
EDITED
try this
var cururl = window.location.href;
jQuery("rs-layer[id|='"+cururl.split('/')[3]+"'] , .rs-layer[href='"+cururl+"']").each(function(){
jQuery(this).addClass("current-slider-menu");
});
I solved it like this instead, skipping the whole idea with text-decoration.
I added an arrow. Finished.
JS:
var url = window.location.href;
var msg = document.getElementById('current-menu-item-arrow');
if( url.search( 'my-word' ) > 0 ) {
msg.style.display = "block";
}
CSS:
#current-menu-item-arrow {display:none;}

How to change a URL parameter on a link that has # as href and is submitted inside a form

I'm working on a drupal module and it gets images from an API, adds selectable search-filters and generates pagination. If I go to e.g. the 7th pagination page and add a filter that only spans 3 pages it will result in not showing anything at all.
Solution: on upon adding a filter, go back to the 1st page. Now is my problem that that page is an url parameter and the links made by the filter are set to href='#' so basically this page yes.
So I try to debug the javascript that handles the on click:
$('#blabla .filter-url').click(function(e) {
e.preventDefault();
var link = $(e.currentTarget);
console.log(link);
var filter_key = link.data('filter-key');
var filter_value = link.data('filter-value');
// var active = link.hasClass('active');
var filters_input = $('#blabla input[name="filters"]');
var current_filters = JSON.parse(filters_input.val() || '{}');
current_filters.filters = current_filters.filters || [];
var exists = ($.grep(current_filters.filters, function(e, i){
return e.key == filter_key;
}).length);
if (exists) {
//Remove current filter from list
current_filters.filters = $.grep(current_filters.filters, function(e, i){
return e.key != filter_key;
});
link.removeClass('active');
}
// Add current filter to list
current_filters.filters.push({
key: filter_key,
value: filter_value,
});
link.addClass('active');
filters_input.val(JSON.stringify(current_filters));
$('#formname').submit();
});
the link object:
The link object has a {0, context and length} object in which both 0 and context contain multiple instances of the url, which one should I edit?
I just want to manipulate the URL / get parameter page=xxx to be page=0, so it goes back to the 1st page. How to achieve this?
I was searching in the wrong place. At the end of the onclick-function it submits the form. I had to change the action of this form like this:
var old_form_action = $('#formname').attr('action');
var new_form_action = old_form_action.replace(/(page=)[^\&]+/, '$1' + '0');
$('#formname').attr('action', new_form_action);

jQuery Finding Script Tags in AJAX Response String

I'm pulling an AJAX response HTML string with jQuery. I have some colliding scripts when I append this response to the document, so I wanted to remove it, and place it only after the offending original scripts are removed.
Here is my code (located in the success function of the ajax):
var content = $(response).find('.content').html();
var scripts = $(content).find('script');
console.log(scripts);
This code returns 0 scripts. However, when I do:
var content = $(response).find('.content').html();
var scripts = $(content).find('h3'); //PULLING H3s INSTEAD OF SCRIPT TAGS
console.log(scripts);
It returns all of the h3's in that string. What's going on here?
I can confirm that the script IS in the response string.
Thanks all for the help. I ended up using hidden inputs in the documents, then using $.getScript() on the values of those. Everything is working, now.
the script tags are stripped and executed when you do $(response). Instead, you should use a regexp to replace script tags with divs, then after you turn it into DOM Nodes, select said divs, iterate over them, and process them.
One way of doing that is:
function cleanInsert(html, target, htmlSelector, filter) {
var outHTML = html, $content = $(target);
outHTML = outHTML.replace(/<script/ig, "<div class='iscript'").replace(/<\/script/ig, '</script');
outHTML = $("<div>").html(outHTML);
outHTML = htmlSelector ? outHTML.find(htmlSelector) : outHTML.children();
if (filter) {
outHTML = filter.call(outHTML);
}
var scripts = outHTML.filter('div.iscript').detach();
scripts.add(outHTML.find('div.iscript').detatch());
$content.html(outHTML);
scripts.each(function() {
var $this = $(this),
s = document.createElement("script");
if ($this.attr('src') != "") {
s.src = $this.attr('src');
} else {
s.nodeValue = $this.text();
}
$content[0].appendChild(s);
});
}​
// insert target response filter
cleanInsert(response, "#targetel", ".content");
not heavily tested.

How to get the text after the # symbol in a link?

I have a simple link with a hashtag in it. ie:
<a class="page_navigation" href="#something">click</a>
On clicking this, I would like to just end up with the 'something' part (minus the hash) in a var.
So far I have
$('.page_navigation').click(function(e)
{
e.preventDefault();
var href = $(this).attr('href');
});
Obviously I just end up with '#something' in my href var with the above code, and I understand I could do some kind of regex (not sure how yet) to strip the #, but I wonder if there is an easier way to access this part of the href I'm unaware of, without having to go through some find and replace code.
Any ideas?
Note: I also know I could store the 'something' in a data tag, but I'm trying to keep this code as DRY as possible.
If you know it has a # in it, you can use this:
$('.page_navigation').click(function(e)
{
e.preventDefault();
var hash = this.href.replace(/^.*#/, "");
});
If you don't know whether it has one it it or not, you can use this:
$('.page_navigation').click(function(e)
{
e.preventDefault();
var hash = "";
if (this.href.indexOf("#") {
hash = this.href.replace(/^.*#/, "");
}
});
In HTML5, you could use:
this.hash
but that is only for the latest browsers.
var theHash = $(this).prop("hash").substr(1);
Related answer to another question
Demo http://jsfiddle.net/UR3XN/
code
$('.page_navigation').click(function(e)
{
e.preventDefault();
var href = $(this).attr('href');
var equalPosition = href.indexOf('#'); //Get the position of '#'
var withouthash = href.substring(equalPosition + 1);
alert(withouthash);
});​
You don't need regular expressions for this. You can simply do
var fragment;
if (window.location.hash) {
fragment = window.location.hash;
}
Note that this will pick up the # symbol as well. So,
fragment = "#something"
If you don't want the # symbol, use substring like this:
fragment = window.location.hash.substring(1)
If you want to pick out the hash fragment from an anchor tag, you can do this:
var link = $('#yourAnchor').attr('href');
var fragment;
if (link.indexOf("#") !== -1) {
fragment = link.substr(link.indexOf("#") + 1);
}

Jquery script freezing browser but working

i'm trying to make a live search for my mobile website, I don't want to query the database every time a user type a letter so I created a ordered list with all the names that can be searched for and i'm looping through it with jquery, problem is that I have 3300 names and it's freezing the browser when it searches through them, can anyone give me a tip about better ways to do it? here is my code:
$(document).ready(function(){
$("input#search").keyup(function(){
var filter = $(this).val(), count = 0;
var html = "";
$("ol.pacientes li").each(function(){
var nome_paciente = $(this).text();
if(nome_paciente.indexOf(filter.toUpperCase()) != -1){
html = html + " " + nome_paciente;
}
$('#pacientes_hint').html(html);
});
Use the jQuery autocomplete version. You can load an array with all your names and pass it in to autocomplete, which will work on the fly.
http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/
You could change your each to:
var text = $("ol.pacientes li:contains(\""+filter.toUpperCase()+"\")").map(function() {
return $(this).text();
}).join(' ');
$('#pacientes_hint').text(text);
Besides being shorter, the only improvement will be setting the contents of $('#pacientes_hint') only at the end, which could help.
Let me know if you need a more creative solution.
First of all, you could move #pacientes_hint outside the each function.
$(document).ready(function(){
$("input#search").keyup(function(){
var filter = $(this).val(), count = 0;
var html = "";
$("ol.pacientes li").each(function(){
var nome_paciente = $(this).text();
if(nome_paciente.indexOf(filter.toUpperCase()) != -1){
html = html + " " + nome_paciente;
} // end if
}); // end each
$('#pacientes_hint').html(html);
Then, you can define ol.pacientes as a variable before the keyup handler, so it doesn't look for it everytime and in the each function, search inside the variable:
$(document).ready(function(){
var pacientes_list = $("ol.pacientes");
var pacientes_hint = $("#pacientes_hint");
$("input#search").keyup(function(){
...
$("li", $(pacientes_list)).each(function(){ // search in the container
...
}); // end each
$(pacientes_hint).html(html);

Categories