I am experimenting with making a one page app with a header and an iframe for the content of the page. So... I made a little javaScript controller to do so. It takes an enter code hereobject named routes to handle clicks on some of the anchor tags which I want to trigger a change in the iFrames url. This is all working fine for me, but when I go to use the back button it does not seem to be aligned correctly.
this is where I got the idea: http://gtv-resources.googlecode.com/svn/trunk/examples/location-hash-html.html#3
here is the article that google has written on it: https://developers.google.com/tv/web/articles/location-hash-navigation
<script src="controller.js"></script>
<script>
var routes = {
"view":"viewFrame",
"index": {
"name": "main",
"location": "subpages/landing.html"
},
"paths": {
"about": "subpages/about.html",
"download": "subpages/download.html",
"main":"subpages/landing.html"
}
};
</script>
</head>
<body>
<ul>
<li><a class='handle' data-link='main'>Back To Main Page</a>
</li>
<li><a class='handle' data-link='about'>About</a>
</li>
<li><a class='handle' data-link='download'>Download</a>
</li>
</ul>
<iframe id="viewFrame" src="subpages/landing.html">
</body>
and my js file
window.onload = function() {
if (routes) {
var View = routes,
flag = true;
View.update = function(hashValue, flag) {
console.log('ok2')
var frame = document.getElementById('viewFrame');
frame.src = routes.paths[hashValue]
if (flag) {
View.setHash(hashValue);
}
};
View.getHash = function() {
return window.location.hash.substring(1);
}
View.setHash = function(str) {
flag = false;
window.location.hash = str;
}
window.onhashchange = function(e) {
if (flag) {
View.update(getLocationHash(), false);
} else {
flag = true;
}
};
var hashValue = View.getHash(),
handles = document.querySelectorAll('.handle');
for (var i = 0; i < handles.length; i++) {
console.log(handles[i]);
handles[i].addEventListener('click', evTrigger)
}
function evTrigger() {
console.log(this)
var link = this.getAttribute('data-link')
View.update(link, true)
}
if (hashValue == '') {
View.update(routes.index.name, true);
}
}
};
if you can interpret my madness I would be thankful for the help.
Related
I'm adding a "remove all" button to my chrome extension which as the name suggests should serve to remove all saved links.
The button works only after I have performed some other action first (adding a link, removing a link etc) but of course, I want it to work right away.
I have read that this may be due to the code being asynchronous so I tried introducing a callback function with the help of this question: Add callback to .addEventListener however, it's still performing the same way it did before so maybe that wasn't the issue after all, or I may have read the other question wrong. I appreciate any tips so thank you in advance. I will try to figure it out myself in the meantime.
var urlList = [];
var i = 0;
document.addEventListener('DOMContentLoaded', function() {
getUrlListAndRestoreInDom();
// event listener for the button inside popup window
document.getElementById('save').addEventListener('click', addLink);
});
function addLink() {
var url = document.getElementById("saveLink").value;
addUrlToListAndSave(url);
addUrlToDom(url);
}
function getUrlListAndRestoreInDom() {
chrome.storage.local.get({
urlList: []
}, function(data) {
urlList = data.urlList;
urlList.forEach(function(url) {
addUrlToDom(url);
});
});
}
function addUrlToDom(url) {
// change the text message
document.getElementById("saved-pages").innerHTML = "<h2>Saved pages</h2>";
var newEntry = document.createElement('li');
var newLink = document.createElement('a');
var removeButton = document.createElement('button');
removeButton.textContent = "Remove";
removeButton.type = "button";
removeButton.className = "remove";
removeButton.addEventListener("click", function() {
var anchor = this.previousElementSibling;
var url = anchor.getAttribute("href");
removeUrlAndSave(url);
this.parentNode.remove();
});
newLink.textContent = url;
newLink.setAttribute('href', url);
newLink.setAttribute('target', '_blank');
newEntry.appendChild(newLink);
newEntry.appendChild(removeButton);
newEntry.className = "listItem";
document.getElementById("list").appendChild(newEntry);
}
function removeUrlAndSave(url) {
var index = urlList.indexOf(url);
if (index != -1) {
urlList.splice(index, 1);
saveUrlList();
}
}
function addUrlToListAndSave(url) {
urlList.push(url);
saveUrlList();
//}
}
function saveUrlList(callback) {
chrome.storage.local.set({
urlList
// }, function() {
// if (typeof callback === 'function') {
// //If there was no callback provided, don't try to call it.
// callback();
// }
// });
});
function removeMe(i) {
var fullList = documents.getElementsByClassName('listItem');
listItem[i].parentNode.removeChild(listItem[i]);
}
function removeAll() {
var removeList = document.getElementsByClassName("listItem");
while (removeList[0]) {
removeList[0].parentNode.removeChild(removeList[0]);
};
}
function registerElement(callback) {
var element = document.getElementById("remove-all-button");
element.addEventListener("click", callback);
}
registerElement(removeAll);
#list {
min-height: 360px;
max-height: 360px;
width: 300px;
margin: auto;
overflow: scroll;
}
<head>
<script type="text/javascript" src="popup.js"></script>
<link rel="stylesheet" href="popup.css">
</head>
<body>
<div>
<span id="hot-button">Hot Drops</span>
<li id="removeAll">
<button id="remove-all-button"> Remove All</button>
</li>
<span id="saved-pages"></span>
<div>
<ul id="list"></ul>
</div>
</div>
<input type="button" id="save" value="Add">
<input type="text" id="saveLink" name="member" value=""><br/>
<span id="settings-button">Settings</span>
</body>
</html>
there you go
jsfiddle
had to write this line to post link
http://jsfiddle.net/1w69bo8k/ - you made a lot of mistakes, where you put certain code, to using variables I never saw them defined anywhere in code
(you keep editing the question, I went from this fiddle you provided)
change back to your getUrlListAndRestoreInDom function, deleted the storage code
you update the storage and the urlList manually, rather do it after the update of local is successful
I can't seem to figure out how to make my site navigation have an active link for the current page.
This is the only code that is working for me, however, there is always two links with the class "active." I only want the current page to be active.
Here is my code:
<script>
function setActive() {
aObj = document.getElementById('nav').getElementsByTagName('a');
for(i=0;i<aObj.length;i++) {
if(document.location.href.indexOf(aObj[i].href)>=0) {
aObj[i].className='active';
}
}
}
window.onload = setActive;
</script>
Here is my staging site: http://champhero.wpengine.com
Thanks for any help!
You are checking an indexOf. Therefore, URL http://champhero.wpengine.com/ is always contained in others like http://champhero.wpengine.com/the-enemies/
If you just check an equality, it should work:
function setActive() {
var aObj = document.getElementById('nav').getElementsByTagName('a');
for (var i = 0; i < aObj.length; i++) {
if (document.location.href == aObj[i].href) {
aObj[i].className = 'active';
}
}
}
Note: You were not declaring local variables with 'var', making them globals and potentially unstable across the environment. i changed that in my suggested code.
a tag href contains whole link so you could check for equality like below.
<script>
function setActive() {
aObj = document.getElementById('nav').getElementsByTagName('a');
for(i=0;i<aObj.length;i++) {
if(document.location.href === aObj[i].href) {
aObj[i].className='active';
}
}
}
window.onload = setActive;
</script>
Home page nav link(http://champhero.wpengine.com/) is highlighted in every page because it's present in all other links(http://champhero.wpengine.com/pagelink)
<script>
window.onload = function(){
var anchors = document.getElementsByTagName('a');
for (var i = 0; i < anchors.length; ++i)
if (anchors[i].href === window.location.href)
anchors[i].className += ' active';
};
</script>
though this snippet will apply the class to all anchors. For just the ones in, say, your navigation bar, give them a specific CSS class to hook into and then:
<script>
window.onload = function(){
var nav_links = document.querySelectorAll('.nav-link');
for (var i = 0; i < nav_links.length; ++i)
if (nav_links[i].href === window.location.href)
nav_links[i].className += ' active';
};
</script>
Hi I have the below page where you simply click the button Full screen and the page browser takes up the full screen, the navigation controls are also hidden to - which is what I like. However if you page refresh (or in my case my page refreshes every 5 minutes) the navigation controls return and it is no longer the view as previous. How can I solve this so that when it refreshed the navigation etc doesn't return and it remains full screen?
<html>
<head>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" />
<script src="screenfull.js"></script>
<script>
$(function () {
$('#supported').text('Supported/allowed: ' + !!screenfull.enabled);
if (!screenfull.enabled) {
return false;
}
$('#request').click(function () {
screenfull.request($('#container')[0]);
// does not require jQuery, can be used like this too:
// screenfull.request(document.getElementById('container'));
});
$('#exit').click(function () {
screenfull.exit();
});
function fullscreenchange() {
var elem = screenfull.element;
$('#status').text('Is fullscreen: ' + screenfull.isFullscreen);
if (elem) {
$('#element').text('Element: ' + elem.localName + (elem.id ? '#' + elem.id : ''));
}
if (!screenfull.isFullscreen) {
$('#external-iframe').remove();
document.body.style.overflow = 'hidden';
}
}
document.addEventListener(screenfull.raw.fullscreenchange, fullscreenchange);
// set the initial values
fullscreenchange();
});
</script>
<button id="request"><i class="fa fa-arrows-alt"></i> Request</button>
<button id="exit">Exit</button>
</body>
(function () {
'use strict';
var isCommonjs = typeof module !== 'undefined' && module.exports;
var keyboardAllowed = typeof Element !== 'undefined' && 'ALLOW_KEYBOARD_INPUT' in Element;
var fn = (function () {
var val;
var valLength;
var fnMap = [
[
'requestFullscreen',
'exitFullscreen',
'fullscreenElement',
'fullscreenEnabled',
'fullscreenchange',
'fullscreenerror'
],
// new WebKit
[
'webkitRequestFullscreen',
'webkitExitFullscreen',
'webkitFullscreenElement',
'webkitFullscreenEnabled',
'webkitfullscreenchange',
'webkitfullscreenerror'
],
// old WebKit (Safari 5.1)
[
'webkitRequestFullScreen',
'webkitCancelFullScreen',
'webkitCurrentFullScreenElement',
'webkitCancelFullScreen',
'webkitfullscreenchange',
'webkitfullscreenerror'
],
[
'mozRequestFullScreen',
'mozCancelFullScreen',
'mozFullScreenElement',
'mozFullScreenEnabled',
'mozfullscreenchange',
'mozfullscreenerror'
],
[
'msRequestFullscreen',
'msExitFullscreen',
'msFullscreenElement',
'msFullscreenEnabled',
'MSFullscreenChange',
'MSFullscreenError'
]
];
var i = 0;
var l = fnMap.length;
var ret = {};
for (; i < l; i++) {
val = fnMap[i];
if (val && val[1] in document) {
for (i = 0, valLength = val.length; i < valLength; i++) {
ret[fnMap[0][i]] = val[i];
}
return ret;
}
}
return false;
})();
var screenfull = {
request: function (elem) {
var request = fn.requestFullscreen;
elem = elem || document.documentElement;
// Work around Safari 5.1 bug: reports support for
// keyboard in fullscreen even though it doesn't.
// Browser sniffing, since the alternative with
// setTimeout is even worse.
if (/5\.1[\.\d]* Safari/.test(navigator.userAgent)) {
elem[request]();
} else {
elem[request](keyboardAllowed && Element.ALLOW_KEYBOARD_INPUT);
}
},
exit: function () {
document[fn.exitFullscreen]();
},
toggle: function (elem) {
if (this.isFullscreen) {
this.exit();
} else {
this.request(elem);
}
},
raw: fn
};
if (!fn) {
if (isCommonjs) {
module.exports = false;
} else {
window.screenfull = false;
}
return;
}
Object.defineProperties(screenfull, {
isFullscreen: {
get: function () {
return Boolean(document[fn.fullscreenElement]);
}
},
element: {
enumerable: true,
get: function () {
return document[fn.fullscreenElement];
}
},
enabled: {
enumerable: true,
get: function () {
// Coerce to boolean in case of old WebKit
return Boolean(document[fn.fullscreenEnabled]);
}
}
});
if (isCommonjs) {
module.exports = screenfull;
} else {
window.screenfull = screenfull;
}
})();
Online Demo : https://plnkr.co/edit/zx0rXwXpJbWdMvh3HQ25?p=preview
Make onepage website (ajax) (no refresh) Use history pushstate to save all your links so you can use history navigation and change your URL. (most of time I use this approach.)
Or you can use localstorage to save state.
Theoretically You can store an indication of what was the previews state (full-screen / normal) in the browser storage.
Then on page load, read the stored value and activate full-screen if necessary.
However, modern browsers require this to be an interactive user action (not automatically via script on load)
If you try to automate this, you'll get these type of warnings in the browser's console:
Alternatives
Avoid full refreshes
Workaround using custom browser extension to restore the fullscreen state
Hi there i am trying to get current url of the active tab in my popup.js file and below is the code i am using but somehow it's not working so can you please help me what's wrong with it. Thank you in advance.
function getAmazonURL()
{
alert("ok");
$url = "";
chrome.windows.getAll({
}, function(windows) {
for (var i in windows) {
var tabs1 = windows[i].tabs;
for (var j in tabs1) {
var tab = tabs1[j];
if(tab.active)
{
$url = tab.url;alert(tab.url);
}
}
}
});
}
document.addEventListener('DOMContentLoaded', function () {
getAmazonURL();
});
To get the active tab all you have to do is use chrome.tabs.query. For example:
chrome.tabs.query({active:true,currentWindow:true},function(tab){
//Be aware that `tab` is an array of Tabs
console.log(tab[0].url);
});
function getAmazonURL()
{
$chromeurl = "";
chrome.windows.getAll({
"populate":true
}, function(windows) {
for (var i in windows) {
var tabs = windows[i].tabs;
for (var j in tabs) {
var tab = tabs[j];
if(tab.active)
{
$chromeurl = tab.url;
}
}
}
alert($chromeurl);
return $chromeurl;
});
}
document.addEventListener('DOMContentLoaded', function () {
getAmazonURL();
});
Need some help with the script below. I would like to add the ability to pass a url parameter that would open one of the tabs based on the URL#tabinfo. Any help would be great thanks.
(function ($) {
function getactTabAnc() {
return this.find('.active>a')[0];
}
function getContentId(tabAnchorS) {
return $(tabAnchorS).attr('href').replace('#', '');
}
function applyStyles(newActTabAnc) {
var actTabAnc = newActTabAnc || getactTabAnc.apply(this), activeContentId = getContentId(actTabAnc);
this.find('a').each(function () {
var $cur = $(this), curContentId = getContentId(this);
if (activeContentId === curContentId) {
$cur.closest('li').addClass('active');
$('#' + curContentId).show();
}
else {
$cur.closest('li').removeClass('active');
$('#' + curContentId).hide();
}
});
}
$.fn.tabs = function () {
return this.each(function () {
var $tabTainer = $(this);
applyStyles.apply($tabTainer);
$tabTainer.find('a').click(function (e) {
console.log('clicked');
var actTabAnc = getactTabAnc.apply($tabTainer), isActive = this === actTabAnc;
e.preventDefault();
if (!isActive) {
applyStyles.apply($tabTainer, [this]);
}
});
});
};
})(jQuery);
<ul id="tabsHolder">
<li class="active">Header 1</li>
<li>Header 2</li>
</ul>
<div id="tabId1">Content 1</div>
<div id="tabId2">Content 2</div>
Look at window.location.hash and onhashchange event. If ('onhashchange' in window) is false then you need to poll for the hash changing.
There exists libraries to abstract this away.