I need to show a DIV on two pages (URL's) but not on the others.
(I have jQuery on the pages if that helps.). I'm a complete noob so all help is very much appreciate. Thank's!
Case (1) where I want to show the DIV:
On the start page, when the web browser address field reads 'www.mydomin.com'
The start page is PHP so I guess the full URL is 'www.mydomin.com/index.php'
Case (2):
'www.mydomin.com/index.php?option=com_myblog&title.html&Itemid=1&lang=en'
WHERE this part is alway the same
'www.mydomin.com/index.php?option=com_myblog&'
AND this part is always unique
'title.html&Itemid=1&lang=en
Example
if (url == 'www.mydomin.com' or 'www.mydomin.com/index.php?option=com_myblog&') {
do this
xxxxxxxx
else
nothing
This should work, if I understand the question correctly
var url = document.location.href;
if (url.indexOf('www.mydomin.com/index.php?option=com_myblog&') >= 0) {
$('#div_id').hide();
} else {
$('#div_id').show();
}
But really, if you use PHP anyway, you should figure out how to not render the div in the first place.
You can parse the query string and show/hide the div based on the result.
I also think it should be handled from PHP code instead from JavaScript. And div should not be rendered in first place.
You can target a specific query parameter of the URL using window.location.search. Using the below code, you can find an exact match anddisplay/hide the HTML element:
var firstURLParam = window.location.search.substring(1).split('&')[0];
var datGuiEle = document.getElementById("elemID");
if(firstURLParam == "debug"){
datGuiEle.style.display = "block";
}
else {
datGuiEle.style.display = "none";
}
Related
I am very new to JavaScript. I am trying to make a web application, where a simple back button will go to a specific page I am looking for, one that has the word "search" in it. I don't know the exact URL, because the parameters within that URL change, and I need to keep it consistent to what the user wanted. But this one button should go back to that one page, regardless of the other links that were clicked.
For example:
If I clicked on
Home Page
Main Page
Page 1
Page 1.3
Back
I want the back to always take me to Main Page with the exact parameters it had before, not Home Page.
I tried the following:
The button itself
movieTableBodyElement.append('' + " << Back" + ''); // Building the HTML button, calls the goBackHelper() function
function goBackHelper()
{
// checks if the page directly behind is the Main Page with "search"
if(document.referrer.includes("search"))
{
// if its the main page, exit the function and end recursive call
window.history.go(-1);
}
else
{
// it is not the last page, so go to the past page and check again
window.history.go(-1);
goBackFunction();
}
}
But this takes me to the very first home page. I thought that document.referrer would get me the past URL, but it doesn't seem to be working for me. Is there a way to get the URL from past pages? So if I am on page 2, can I get all the URLs and search for Main Page? Any help is greatly appreciated!
I'm also new to Stack Overflow, so if there is any clarification please don't hesitate to let me know!
document.referrer is not the same as the actual URL in all situations.
Your best bet is to store the URLs in sessionStorage.
Add this snippet of code to your pages:
if (sessionStorage.getItem("locationHistory") !== null) {
var locationHistoryArray = JSON.parse(sessionStorage.getItem("locationHistory"));
locationHistoryArray.push(window.location.href);
sessionStorage.setItem("locationHistory", JSON.stringify(locationHistoryArray));
} else {
var locationHistoryArray = [];
locationHistoryArray.push(window.location.href);
sessionStorage.setItem("locationHistory", JSON.stringify(locationHistoryArray));
}
And this is your goBackHelper() function :
function goBackHelper() {
var searchString = 'search'; //modify this
var locationHistoryArray = JSON.parse(sessionStorage.getItem("locationHistory"));
for (i = 0; i < locationHistoryArray.length; i++) {
if (locationHistoryArray[i].includes(searchString)) {
window.location.assign(locationHistoryArray[i]);
break;
}
}
}
Read about document.referrer here.
Currently, I have a webpage that embeds the following IFRAME:
<iframe src="https://docs.google.com/spreadsheets/u/0/d/1P9DhWOHcl14Y7-P5wCxTm-sUceckGquPoOobO75XhvM/htmlembed/sheet?gid=630924986&single=true" frameborder="0" width="393px" height="385px" style="float:centre" id="MyFrame"></iframe>
The contents of the cells are changed based on formulas. I am trying to find a way that would check if one of the cells (in this case, the cell containing "Foo" listed with a class of "S2" (see here)) contains a string. Depending on the result, it would print different things to the console. For example:
if <"Cell from inside the IFRAME with class S2"> = "stringtosearch"
//found
console.log("The cell contains stringtosearch!")
else
//not found
console.log("The cell does not contain stringtosearch. :( ")
Any help with a way of achieving this would be appreciated! I believe it can be done with jQuery, but I'm not sure on the best way to do it. I'm still new to JS.
Note: I would need to embed this into a Chrome Extension, so I cannot use the option of pulling the Google Sheets API and searching it that way, as Chrome Extensions do not allow Inline Scripting.
Thanks!
Like #DarrenH eluded to in the comments, you have the problem of a cross-domain iframe. If your iframe were on the same domain, you could extract the td of a table like so:
jQuery:
var filteredContents = $('#MyFrame').contents().find('.s2');
if (filteredContents.text() == 'stringtosearch') {
//found
console.log("The cell contains stringtosearch!")
}
else {
//not found
console.log("The cell does not contain stringtosearch. :( ")
}
Vanilla JavaScript:
var iframe = document.getElementById("MyFrame");
var element = iframe.contentWindow.document.getElementsByTagName("td");
for (int i = 0; i < element.length; i++) {
if (element[i].classList.contains('s2')) {
if (element[i].innerText == 'stringtosearch') {
//found
console.log("The cell contains stringtosearch!")
}
else {
//not found
console.log("The cell does not contain stringtosearch. :( ")
}
}
}
I have a multi language site and people come in via links WITH a url suffix (/lang/en for instance) or WITHOUT a suffix (just the page url).
Now I want to create the language switch function with a link (with a class to trigger the javascript).
My link class will be "english" for instance and in the JS I first need to check if there isn't a language suffix to the url already before I append it.
Here's what I have right now (from another thread):
<a class="english" href="">English</a>
<script>
$('.datalink').attr('href', function() {
return this.href + '/lang/en';
});
</script>
This adds the suffix but Without checking if it already exists, how do I check if it is already there and not append it? or change it to another language (/lang/nl)?
UPDATE
Actually my class is not on the href but on the <li> around it, it looks like:
<li class="english"><a title="English">English</a></li>
so now I have
$('.english >a').attr('href', function() {
var suffix = this.href.match(/lang\/en\/?$/i) ? "" : "/lang/en";
return this.href + suffix;
});
NOTE Wat I want to achieve is two links on each page of my website that will consist of the basic page url with a
lang/en
or
lang/nl
suffix to them. When clicked those links will load the same page but with the language suffix in the url, my language plugin will pick that up an present the language.
You can use a regular expression to check if the URL contains the suffix:
if (this.href.match(/lang\/en\/?$/i)) {
/* CONTAINS THE SUFFIX */
} else {
/* DOESN'T CONTAIN IT */
}
The way that I'd probably do it is as follows:
$('.datalink').attr('href', function() {
// suffix is blank if the URL already contains the language portion
var suffix = this.href.match(/lang\/en\/?$/i) ? "" : "/lang/en";
return this.href + suffix;
});
Somehow the none of the above javascript worked for me, I don't know what I was doing wrong but finayl I decided to resort to php cause I understand that much better. I use this on a wordpress site and I came up with the following code (in theme functions.php) that worked for me:
// add languages to menu
add_filter('wp_nav_menu_items','add_langs', 10, 2);
function add_langs($items, $args)
{
if( $args->theme_location == 'primary-menu')
$current_url = ( is_ssl() ? 'https://' : 'http://' ) . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$href = str_replace(array('/lang/en','/lang/nl'),'',$current_url);
$english = '<li class="english">EN</li>';
$nederlands = '<li class="nederlands">NL</li>';
return $items . $english . $nederlands ;
}
This finds my menu called "primary-menu" and adds two items to this menu consisting of $english and $nederlands links.
I had to get the page url with $_server['HTTP_HOST'] instead of get_permalink() cause that one returned a random url somehow. the first one always works and with the str_replace I replace the language additions first if they exist (str_replace doesn't need an if statement, it always checks if it exists before replacing)
Hope this helps someone else out, still wondering why the javascript didn't work for me!
if it is a suffix that always starts with /lang, try this
Live Demo
$('.english a').each(function() {
$(this).attr('href', this.href.split("/lang")[0] + '/lang/en');
});
or if you want to keep one if there
$('.english a').each(function() {
var href = this.href;
var pos = href.indexOf("/lang/");
if (pos == -1) $(this).attr('href', href.substring(0,pos)+'/lang/en');
});
I'm trying to dynamically set the thumbnail shown when sharing to Facebook using javascript. I tried adding the meta tag "og:image" to the page (it's a JSP) and that works, but what I want to do now is to replace such image with another one dynamically loaded by javascript.
Basically, the page is calling an API upon loading, using javascript, and retrieves a list of images. I want to use one of those as the thumbnail.
I tried using javascript to replace the content of the meta tag, but Facebook doesn't seem to care abou t it (it does change if I check with my browser).
Is it possible to do this?
Thanks in advance!
Here is a function I used to extract the image url from a flash object tag's flashvars parameter, and then assign it to a meta tag by using jquery:
$(window).load(function(){
//Use $(window).load() instead of $(document).ready(), so that the flash code has loaded and you have all the html you need process with javascript already in place when you start processing.
var stringToExtractFrom = $('param[name="flashvars"]').attr('value');
//Get the flashvars parameter value which we'll use to extract the preview image url from.
var pos = stringToExtractFrom.indexOf("&");
//Search for the position ampersand symbols which surround the image url.
var stringToUse;
//The final string we'll use.
var startOfImageSrc = null;
//The first position where we discover the ampersand
var endOfImageSrc;
//The second position where we discover the ampersand
var lengthToSubstract
//How many symbols to chop off the flashvars value.
while(pos > -1) {
if(startOfImageSrc == null){
startOfImageSrc = pos;
}
else {
endOfImageSrc = pos;
lengthToSubstract = endOfImageSrc - startOfImageSrc;
}
pos = stringToExtractFrom.indexOf("&", pos+1);
}
stringToUse = stringToExtractFrom.substr(startOfImageSrc+7, lengthToSubstract-7);
$('meta[property="og:image"]').attr('content', stringToUse); });
Facebook robot never runs a java script code
but why you don't try to set og tags in in server-side ?
Here's the scenario:
I have a link on "page1.html" that i want to get displayed on an iframe of another link "page2.html" .
How do I do this?
Fourth and final try!
The problem with your page is the following
Your problem is that your link [See adoptable dogs] points to http://hssv.convio.net/PageServer?pagename=adoption_available?http://adopt.hssv.org/search/searchResults.asp?task=search&searchid=&advanced=&s=adoption&animalType=3%2C16&statusID=3&submitbtn=Find+Animals
When I go to
http://hssv.convio.net/PageServer?pagename=adoption_available,
I'm redirected to
http://hssv.convio.net/site/PageServer?pagename=page_not_found
Therefore I assume the correct link is http://hssv.convio.net/site/PageServer?pagename=adoption_available (yup, that loaded a page correctly, you were missing /site/ within the link)
Now the second part of your problem. Your page that contains an iframe expected the name of the page to load into the iframe to be everything after the '?', which was fine before since you were't using any other params in the URL (actually not fine, since it breaks easily)
so your link should be (note that the url passed as a parameter should be url encoded)
http://hssv.convio.net/site/PageServer?pagename=adoption_available&content=http%3A%2F%2Fadopt.hssv.org%2Fsearch%2FsearchResults.asp%3Ftask%3Dsearch%26searchid%3D%26advanced%3D%26s%3Dadoption%26animalType%3D3%2C16%26statusID%3D3%26submitbtn%3DFind%2BAnimals
And your page containing the iframe should modify LoadContent to the following.
function LoadContent() {
var url = getParams()['content'];
if (url) {
LoadIFrame(url);
}
}
function getParams() {
var paramMap = {};
if (location.search.length == 0) {
return paramMap;
}
var parts = location.search.substring(1).split("&");
for (var i = 0; i < parts.length; i ++) {
var component = parts[i].split("=");
paramMap [decodeURIComponent(component[0])] = decodeURIComponent(component[1]);
}
return paramMap;
}
Lastly, I don't want to sound rude, but it seems like you need to do some studying before you are assigned to modify these pages. These are all very basic concepts of HTML, HTTP, and JS. Some debugging would easily identify your problem and it had nothing to do with what you asked initially, it was simply that you modified code without a clue to what it was doing...