Changing Attribute with Javascript-Header Problems - javascript

The following HTML displays a fancy font on my site, due some alterations I made to <h2>
<section id="content">
<article>
<h2 id="titletext">Welcome to <span>Pomona High School!</span></h2>
<p id="infotext" style="width: 773px; height: 28px;" >Welcome to the new Pomona High School site! Please give us feedback!</p>
<br />
</article>
</section>​
This displays quite fine in the site.
When the user now goes to the taskbar and chooses one of the submenu items, the <h2> text will change to a specified string value. I went into the Javascript editor and produced the following.
window.onhashchange = function() { //when the hash changes (the '#' part)
var loc = window.location + ""; //get the current location (from the address bar)
var curHash = loc.substr(loc.lastIndexOf("#")); //get what's after the '#'
if (curHash == "#mission") { //else if it's #mission
document.getElementById('titletext').innerHTML = 'Mission Statement';
}
else {
document.getElementById('titletext').innerHTML = 'Welcome to Pomona High School';
}
};​
Linking one of the menu items to #mission, I was succesful in changing the text. But the font changed to the default <h2> font.
I need help on how to bring my custom font onto strings in Javascript. Thanks in advance!
CSS stylsheet for <h2>:
h2 {
font-size: 30px;
line-height: 1.2em;
font-weight: normal;
color: #212222;
margin-bottom: 22px;
}
h2 span {
color: #8a8a8a;
}
And here's the two custom font files (too big to copy and paste to Stack Overflow):-
Regular Font
Light Font

Your code is actually replacing
Welcome to <span>Pomona High School!</span>
with
Welcome to Pomona High School!
Notice, no element. Just set it with the span tag, and you will be fine.

Source: MDN Docs
Here's what MDN has to say about this:
The hashchange event fires when a window's hash changes (see
location.hash).
Syntax:-
window.onhashchange = funcRef;
<body onhashchange="funcRef();">
window.addEventListener("hashchange", funcRef, false);
I think that passing function() { ... } is a function reference but could you try defining the function first and then passing a named reference? The code would go:
function hashChange() { //when the hash changes (the '#' part)
var loc = window.location + ""; //get the current location (from the address bar)
var curHash = loc.substr(loc.lastIndexOf("#")); //get what's after the '#'
if (curHash == "#mission") { //else if it's #mission
document.getElementById('titletext').innerHTML = 'Mission Statement';
}
else {
document.getElementById('titletext').innerHTML = 'Welcome to Pomona High School';
}
};
window.onhashchange = hashChange;
​
OK, I'm confused. There must be something else going on as it's working for me in this JSFiddle...
Your code removes the <span> in the <h2> on hash change which was presumably giving the styling. So it should really be:
window.onhashchange = function() { //when the hash changes (the '#' part)
var loc = window.location + ""; //get the current location (from the address bar)
var curHash = loc.substr(loc.lastIndexOf("#")); //get what's after the '#'
if (curHash == "#mission") { //else if it's #mission
document.getElementById('titletext').innerHTML = '<span>Mission Statement</span>';
}
else {
document.getElementById('titletext').innerHTML = 'Welcome to <span>Pomona High School</span>';
}​
}
Also, I think you're mixing up the if and else statements. This:
else if(curHash == "#mission") {
...
}
else {
...
}
should really be:
if(curHash == "#mission") {
...
}
else if {
...
}

Related

javascript to add class to body based on url

I have two domains and both have the same web page. Same HTML CSS and content.
foo.com and bar.com
Both websites reside in the same hosting and return the same files. This way I don't have to duplicate the changes in both domains. I just edit one file and both domains are updated.
Now I want to change some colors on foo.com and hide some elements on bar.com but still don't want to duplicate the website.
I want a JavaScript code snippet that can detect the current URL of the page and add class to the body. It would be nice if there is something that can detect only domain.
Try this..
if(window.location.href == 'https://stacksnippets.net/js'){
$("#demo").addClass('demoClass');
}
.demoClass{
color: green;
background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="demo">Color changed as per url change</p>
put below in script at the end of body:
You can use jquery as well. In short use documet/winod load event to put your host based logic.
window.addEventListener('load', function() {
var isFoo = window.location.href.indexOf('foo.com') > -1;
var body = document.getElementsByTagName("body")[0];
var class = isFoo ? 'foo-class' : 'bar-class';
body.className = body.className + ' '+ class;
})
Try using Window.location in javascript. Add some custom logic aswell.
// Get the current browser url.
const url = window.location.href;
console.log(url);
// Selecting the body tag
const body = document.getElementsByTagName("BODY")[0];
// Adding a custom check to check whether the url contains our domain.
if (url.indexOf('stacksnippets') > -1) {
body.className += ' class-one';
} else {
body.className += ' class-two';
}
.class-one {
color: blue;
}
.class-two {
color: green;
}
<body>
<h2>JavaScript</h2>
<h3>The window.location object</h3>
</body>

How can I prevent pop up box when hovering over link?

I am trying to fix my webpage. I have a small problem. When I hover over my link this pop up box covers the text. What would be the best method to fix this? Thanks for any tips
I have added an img below for better understanding.
http://imgur.com/a/Nwqv4
<html>
<head>
<title>010101010101010110101010010101010101010110101010</title>
<link rel="shortcut icon" type="image/png" href="red.png"/>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<style type="text/css">
body {
background-color: black
}
#console {
font-family: courier, monospace;
color: white;
width:750px;
margin-left:auto;
margin-right:auto;
margin-top:100px;
font-size:14px;
}
#x {
color: red;
}
#d {
color: #0f0;
}
a {
color: white;
text-decoration: none;
}
#a {
color: #0f0;
}
#c {
color: #0bc;
}
#b {
color: #ff0096;
}
#green {
color: green;
}
#red {
color: red;
}
</style>
</head>
<body>
<script type="text/javascript">
var Typer={
text: null,
accessCountimer:null,
index:0, // current cursor position
speed:1, // speed of the Typer
file:"", //file, must be setted
accessCount:0, //times alt is pressed for Access Granted
deniedCount:0, //times caps is pressed for Access Denied
init: function(){// inizialize Hacker Typer
accessCountimer=setInterval(function(){Typer.updLstChr();},600); // inizialize timer for blinking cursor
$.get(Typer.file,function(data){// get the text file
Typer.text=data;// save the textfile in Typer.text
Typer.text = Typer.text.slice(0, Typer.text.length-1);
});
},
content:function(){
return $("#console").html();// get console content
},
write:function(str){// append to console content
$("#console").append(str);
return false;
},
makeAccess:function(){//create Access Granted popUp FIXME: popup is on top of the page and doesn't show is the page is scrolled
Typer.hidepop(); // hide all popups
Typer.accessCount=0; //reset count
var ddiv=$("<div id='gran'>").html(""); // create new blank div and id "gran"
ddiv.addClass("accessGranted"); // add class to the div
ddiv.html("<h1>ACCESS GRANTED</h1>"); // set content of div
$(document.body).prepend(ddiv); // prepend div to body
return false;
},
makeDenied:function(){//create Access Denied popUp FIXME: popup is on top of the page and doesn't show is the page is scrolled
Typer.hidepop(); // hide all popups
Typer.deniedCount=0; //reset count
var ddiv=$("<div id='deni'>").html(""); // create new blank div and id "deni"
ddiv.addClass("accessDenied");// add class to the div
ddiv.html("<h1>ACCESS DENIED</h1>");// set content of div
$(document.body).prepend(ddiv);// prepend div to body
return false;
},
hidepop:function(){// remove all existing popups
$("#deni").remove();
$("#gran").remove();
},
addText:function(key){//Main function to add the code
if(key.keyCode==18){// key 18 = alt key
Typer.accessCount++; //increase counter
if(Typer.accessCount>=3){// if it's presed 3 times
Typer.makeAccess(); // make access popup
}
}else if(key.keyCode==20){// key 20 = caps lock
Typer.deniedCount++; // increase counter
if(Typer.deniedCount>=3){ // if it's pressed 3 times
Typer.makeDenied(); // make denied popup
}
}else if(key.keyCode==27){ // key 27 = esc key
Typer.hidepop(); // hide all popups
}else if(Typer.text){ // otherway if text is loaded
var cont=Typer.content(); // get the console content
if(cont.substring(cont.length-1,cont.length)=="|") // if the last char is the blinking cursor
$("#console").html($("#console").html().substring(0,cont.length-1)); // remove it before adding the text
if(key.keyCode!=8){ // if key is not backspace
Typer.index+=Typer.speed; // add to the index the speed
}else{
if(Typer.index>0) // else if index is not less than 0
Typer.index-=Typer.speed;// remove speed for deleting text
}
var text=Typer.text.substring(0,Typer.index)// parse the text for stripping html enities
var rtn= new RegExp("\n", "g"); // newline regex
$("#console").html(text.replace(rtn,"<br/>"));// replace newline chars with br, tabs with 4 space and blanks with an html blank
window.scrollBy(0,0); // scroll to make sure bottom is always visible
}
if ( key.preventDefault && key.keyCode != 122 ) { // prevent F11(fullscreen) from being blocked
key.preventDefault()
};
if(key.keyCode != 122){ // otherway prevent keys default behavior
key.returnValue = false;
}
},
updLstChr:function(){ // blinking cursor
var cont=this.content(); // get console
if(cont.substring(cont.length-1,cont.length)=="|") // if last char is the cursor
$("#console").html($("#console").html().substring(0,cont.length-1)); // remove it
else
this.write("|"); // else write it
}
}
function replaceUrls(text) {
var http = text.indexOf("http://");
var space = text.indexOf(".me ", http);
if (space != -1) {
var url = text.slice(http, space-1);
return text.replace(url, "" + url + "");
} else {
return text
}
}
Typer.speed=20;
Typer.file="index.txt";
Typer.init();
var timer = setInterval("t();", 30);
function t() {
Typer.addText({"keyCode": 123748});
if (Typer.index > Typer.text.length) {
clearInterval(timer);
}
}
</script>
<div id="console"></div>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-610661-7']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</body>
</html>
.txt
<span id="green">
iIYVVVVXVVVVVVVVVYVYVYYVYYYYIIIIYYYIYVVVYYYYYYYYYVVYVVVVXVVVVVYI+.
tYVXXXXXXVXXXXVVVYVVVVVVVVVVVVYVVVVVVVVVVVVVVVVVXXXXXVXXXXXXXVVYi.
iYXRXRRRXXXXXXXXXXXVVXVXVVVVVVVVXXXVXVVXXXXXXXXXXXXXXRRRRRRRRRXVi.
tVRRRRRRRRRRRRRRRXRXXXXXXXXXXXXXXRRXXXXRRRRXXXXXXXRRRRRRRRRRRRXV+.
tVRRBBBRMBRRRRRRRRRXXRRRRRXt=+;;;;;==iVXRRRRXXXXRRRRRRRRMMBRRRRXi,
tVRRBMBBMMBBBBBMBBRBBBRBX++=++;;;;;;:;;;IRRRRXXRRRBBBBBBMMBBBRRXi,
iVRMMMMMMMMMMMMMMBRBBMMV==iIVYIi=;;;;:::;;XRRRRRRBBMMMMMMMMBBRRXi.
iVRMMMMMMMMMMMMMMMMMMMY;IBWWWWMMXYi=;:::::;RBBBMMMMMMMMMMMMMMBBXi,
+VRMMRBMMMMMMMMMMMMMMY+;VMMMMMMMRXIi=;:::::=VVXXXRRRMMMMMMMMBBMXi;
=tYYVVVXRRRXXRBMMMMMV+;=RBBMMMXVXXVYt;::::::ttYYVYVVRMMMMMMBXXVI+=
;=tIYYVYYYYYYVVVMMMBt=;;+i=IBi+t==;;i;::::::+iitIIttYRMMMMMRXVVI=;
;=IIIIYYYIIIIttIYItIt;;=VVYXBIVRXVVXI;::::::;+iitttttVMMBRRRVVVI+,
;+++tttIttttiiii+i++==;;RMMMBXXMMMXI+;::::::;+ittttitYVXVYYIYVIi;;
;===iiittiiIitiii++;;;;:IVRVi=iBXVIi;::::::::;==+++++iiittii+++=;;
;;==+iiiiiiiiii+++=;;;;;;VYVIiiiVVt+;::::::::;++++++++++iti++++=;;
;;=++iiii+i+++++iii==;;;::tXYIIYIi+=;:::::,::;+++++++++++++++++=;;
;;;+==+ii+++++iiiiit=;;:::::=====;;;::::::::::+++i+++++++++i+++;;;
;;;==+=+iiiiitttIIII+;;;:,::,;;;;:;=;;;::,::::=++++++++==++++++;;;
:;====+tittiiittttti+;;::::,:=Ytiiiiti=;:::::,:;;==ii+ittItii+==;;
;;+iiittIti+ii;;===;;:;::::;+IVXVVVVVVt;;;;;::::;;===;+IIiiti=;;;;
;=++++iIti+ii+=;;;=;:::;;+VXBMMBBBBBBXY=;=;;:::::;=iYVIIttii++;;;;
;;++iiiItttIi+++=;;:::;=iBMMMMMMMMMMMXI==;;,::;;:;;=+itIttIIti+;;;
;=+++++i+tYIIiii;:,::;itXMMMMMMMMMMMBXti==;:;++=;:::::;=+iittti+;;
;;+ii+ii+iitiIi;::::;iXBMMMMMWWWWWMMBXti+ii=;::::,,,,:::=;==+tI+;;
;;iiiitItttti;:::;::=+itYXXMWWWWWWMBYt+;;::,,,,,,,,,,,,,:==;==;;;;
:;=iIIIttIt+:;:::;;;==;+=+iiittttti+;;:,:,,,,::,,,,,,,,:::;=;==::;
;::=+ittiii=;:::::;;;:;:;=++==;;==;:,,,,,,:;::::,,,,,,,,::;==;;::;
:::;+iiiii=;::::,:;:::::;;:;;::;:::,,,,,,,:::;=;;;:,,,,,:::;;::::;
:;;iIIIIII=;:::,:::::::,::::,:::,,,,,,,,,,,:;;=;:,,,,,,::::;=;:::;
:;==++ii+;;;:::::::::::,,,,,,::,,,,,,,,,,,::::,,,,,,,,,,:,:::::::;
::;;=+=;;;:::;;::,,,,,,,,,,,,,,,,,,,,,,,,,:,,,,,,,,,,,,,,,,,:::::;
::;=;;;:;:::;;;;::,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,::,,::::;
:;;:;::::::,::,,:,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,:::;
:::::::::::;;;:,,,,,,,,,,,,,...,...,,,.,,,,,,,,,,,,.,,,,,,,,,,,,:;
::::::::;=;;;;;::,,,,,,,,,,,.......,...,,,,,,,,,,,,.,,,,,,,,,,,,,;
:::::,,:;=;;;;;;;iVXXXVt+:,,....,,,,....,.,,,,,,,.,.....,,,,,,,,:;
:,,::,,:::;;;;;;=IVVVXXXXVXVt:,,,,,..,..,,,,.,,,,,..,.,,,,,,,,,,,;
::,::,,,:,:::::,::;=iIYVXVVVVIYIi;,,.,.,,,::,,,,,,,,,,,,,,,,,,,,,.
:,,,,,,,,,,,,,,,,::;+itIIIIIIi:;;i++=;;;;;;;;;::,,,...,,..,,,,,,,.
:,,,,,,,,,,,,,,=iitVYi++iitt==it;;:;;;;::;;::::,,,......,,,,,,,::.
::,,,,,,,,,,,,,++iiIVIi=;;=;+i;:;+:::,,,,,,,,,,,,,.....,,,,,,,,::,
,,,,,,,,,,,,,,,;=+it=:::,,,,,,,,,,.,......,,.,..........,,,,,,,,::
:,,,,,,,,,,,,,,,,:=:,,,,,,,,,,,,,,......................,.,,.,.,,:
:,,,,,,,,,,,,,,,,,:,,,,,,,,,,..,........................,..,...,,:
,,,,,,,,,,,,,,,,,,,.....................................,.......,,
,,,,,,,,,.,,,,,,,...............................................,,
itittiiiii+=++=;;=iiiiiiittiiiiii+iii===;++iiitiiiiiii+=====+ii=+i
</span>
Let us go for a journey....
It's browser's status bar and you can't turn that off.
In most cases you won't see it and it only shows up when it needs to.
Even if you didn't want it to appear every time you hover over a link, it's one feature that you just can't turn off.
I'd suggest you to move its position to the right.
<a style="float:right;" href="journey.html">Let us go for a journey....</a>
Chrome reads the HREF attribute from your link to display the link in the status bar.
So if you remove the HREF from your A tags, the status bar will not be displayed. However the link won't work either, :). That's why you can create an event handler on MouseOver to address that and keep your links working.
$("body").on('mouseover', 'a', function (e) {
var $link = $(this),
href = $link.attr('href') || $link.data("href");
$link.off('click.chrome');
$link.on('click.chrome', function () {
window.location.href = href;
})
.attr('data-href', href) //keeps track of the href value
.css({ cursor: 'pointer' })
.removeAttr('href'); // <- this is what stops Chrome to display status bar
});
You might run in extra issues, like disabled links or links that have other event handlers. In this case, you can tweak your selector to 'a:not(.disabled)' or perhaps just add this delegation to known elements with the css class ".disable-status", therefore your selector would be: "a.disable-status".
I used a onclick to fix this,
So right now my code is
<div id='link'>
<a id='pro1' onclick="location.href='./pages/langs.html';"></a>
</div>
tht creates another way to use a link without the bar at the bottom, Youd have to use CSS to remove Text Deco ect, or just config links but it works great overall.
For you,
<a onclick="location.href='journey.html';">Let us go for a journey....</a>
CREATES: Let us go for a journey....

codemirror - detect and create links inside editor

I am using codemirror, configured to display javascript.
I have code like this:
...
var ref = 'http://www.example.com/test.html';
var ref2 = 'http://www.example.com/test2.html';
...
When displaying the editor it would be great if I could click on the links that might be present in the editor. The link would open the page on a different tab obviously.
is there an easy way to achieve this ?
Not really easy, but what you'd do is:
Write an overlay mode that recognizes such links. Basically, this is a mode that spits out a custom token type when it finds something that looks like a link, and null otherwise. You can use the simple mode addon to make this easier. You can use this token type's CSS class (for example "link" becomes cm-link) to style your links.
Make your editor use your overlay by calling the addOverlay method.
Register a mousedown event handler on your editor (instance.getWrapperElement().addEventListener(...)).
In this handler, check whether the event's target has the link CSS class. If it does, the user is clicking a link.
If so, use the coordsChar method, using the coordinates from your mouse event, to find the position in the document that was clicked. Extract the actual link from the document text around that position, and follow it.
(Or, even better, instead of directly interfering with the click, which might be intended to put the cursor in the link or select it, show a widget containing a regular link whenever the cursor is inside of link text.)
Here is a solution I came up with:
demo here: plunkr
code:
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.17.0/codemirror.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.17.0/codemirror.css"/>
<style>
html, body { height:100%; }
.CodeMirror .cm-url { color: blue; }
</style>
</head>
<body>
<script>
var cm = CodeMirror(document.body);
cm.setValue('hover over the links below\nlink1 https://plnkr.co/edit/5m31E14HUEhSXrXtOkNJ some text\nlink2 google.com\n');
hyperlinkOverlay(cm);
function hoverWidgetOnOverlay(cm, overlayClass, widget) {
cm.addWidget({line:0, ch:0}, widget, true);
widget.style.position = 'fixed';
widget.style.zIndex=100000;
widget.style.top=widget.style.left='-1000px'; // hide it
widget.dataset.token=null;
cm.getWrapperElement().addEventListener('mousemove', e => {
let onToken=e.target.classList.contains("cm-"+overlayClass), onWidget=(e.target===widget || widget.contains(e.target));
if (onToken && e.target.innerText!==widget.dataset.token) { // entered token, show widget
var rect = e.target.getBoundingClientRect();
widget.style.left=rect.left+'px';
widget.style.top=rect.bottom+'px';
//let charCoords=cm.charCoords(cm.coordsChar({ left: e.pageX, top:e.pageY }));
//widget.style.left=(e.pageX-5)+'px';
//widget.style.top=(cm.charCoords(cm.coordsChar({ left: e.pageX, top:e.pageY })).bottom-1)+'px';
widget.dataset.token=e.target.innerText;
if (typeof widget.onShown==='function') widget.onShown();
} else if ((e.target===widget || widget.contains(e.target))) { // entered widget, call widget.onEntered
if (widget.dataset.entered==='true' && typeof widget.onEntered==='function') widget.onEntered();
widget.dataset.entered='true';
} else if (!onToken && widget.style.left!=='-1000px') { // we stepped outside
widget.style.top=widget.style.left='-1000px'; // hide it
delete widget.dataset.token;
widget.dataset.entered='false';
if (typeof widget.onHidden==='function') widget.onHidden();
}
return true;
});
}
function hyperlinkOverlay(cm) {
if (!cm) return;
const rx_word = "\" "; // Define what separates a word
function isUrl(s) {
if (!isUrl.rx_url) {
// taken from https://gist.github.com/dperini/729294
isUrl.rx_url=/^(?:(?:https?|ftp):\/\/)?(?:\S+(?::\S*)?#)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,}))\.?)(?::\d{2,5})?(?:[/?#]\S*)?$/i;
// valid prefixes
isUrl.prefixes=['http:\/\/', 'https:\/\/', 'ftp:\/\/', 'www.'];
// taken from https://w3techs.com/technologies/overview/top_level_domain/all
isUrl.domains=['com','ru','net','org','de','jp','uk','br','pl','in','it','fr','au','info','nl','ir','cn','es','cz','kr','ua','ca','eu','biz','za','gr','co','ro','se','tw','mx','vn','tr','ch','hu','at','be','dk','tv','me','ar','no','us','sk','xyz','fi','id','cl','by','nz','il','ie','pt','kz','io','my','lt','hk','cc','sg','edu','pk','su','bg','th','top','lv','hr','pe','club','rs','ae','az','si','ph','pro','ng','tk','ee','asia','mobi'];
}
if (!isUrl.rx_url.test(s)) return false;
for (let i=0; i<isUrl.prefixes.length; i++) if (s.startsWith(isUrl.prefixes[i])) return true;
for (let i=0; i<isUrl.domains.length; i++) if (s.endsWith('.'+isUrl.domains[i]) || s.includes('.'+isUrl.domains[i]+'\/') ||s.includes('.'+isUrl.domains[i]+'?')) return true;
return false;
}
cm.addOverlay({
token: function(stream) {
let ch = stream.peek();
let word = "";
if (rx_word.includes(ch) || ch==='\uE000' || ch==='\uE001') {
stream.next();
return null;
}
while ((ch = stream.peek()) && !rx_word.includes(ch)) {
word += ch;
stream.next();
}
if (isUrl(word)) return "url"; // CSS class: cm-url
}},
{ opaque : true } // opaque will remove any spelling overlay etc
);
let widget=document.createElement('button');
widget.innerHTML='→'
widget.onclick=function(e) {
if (!widget.dataset.token) return;
let link=widget.dataset.token;
if (!(new RegExp('^(?:(?:https?|ftp):\/\/)', 'i')).test(link)) link="http:\/\/"+link;
window.open(link, '_blank');
return true;
};
hoverWidgetOnOverlay(cm, 'url', widget);
}
</script>
</body>
</html>
Here is a starting point, but it need to be improved.
LIVE DEMO
function makeHyperLink(innerTextInside)
{
var all = document.getElementsByTagName("*");
for (var i=0, max=all.length; i < max; i++) {
if(all[i].innerText == innerTextInside)
{
all[i].innerHTML="<a target='_blank' href='https://google.com'>THIS IS A LINK TO GOOGLE</a>"
}
}
}

My javascript popup shows for a split second if there's a cookie

I have no clue what I'm doing wrong. It works it just shows the popup for a split second. Would a timeout option be better? Which part is the problem? I'm a little new to Javascript so I don't really know what to exactly look for.
<script language="javascript" type="text/javascript">
/** Create a html cookie and set expiry as a day. **/
function createCookie(name,value,days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = date.toGMTString();
document.cookie = name+"="+value+"; expires="+expires+"; path=/";
}
/** Check if already a cookie has been created. **/
function readCookie(name) {
var flag = 0;
var dcmntCookie = document.cookie.split(';');
for(var i=0;i < dcmntCookie.length;i++) {
var ck = dcmntCookie[i];
while (ck.charAt(0)==' ') {
ck = ck.substring(1,ck.length);
}
if(ck) {
cparts = ck.split('=');
if (cparts[0] == name) flag=1;
}
}
if(flag) {
return true;
} else {
return false;
}
}
/** Check if cookie exists else create a new one. **/
function checkCookie(name) {
if (readCookie(name)) {
document.getElementById('google').style.display = "none";
document.getElementById('google').style.visibility = "hidden";
}
else createCookie(name,"cookie 4 the day",1);
}
</script>
<script type="text/javascript">
function closeThisDiv()
{
var openDiv = document.getElementById('google');
openDiv.style.display = 'none';
}
</script>
<body onLoad="checkCookie('MyCookie')"
If your goal is to have the element with id="google" to be hidden from the very beginning of the page display (so it never shows), then you should add a CSS rule that loads in the head section like this:
#google {display: none;}
Or, you should add a style element to the HTML itself:
<div id="google" style="display:none"></div>
As your code is currently written, it sounds like it is doing what it is supposed to. It waits for the entire document to be loaded (including images) and then it hides the element with id="google". That means the item will show briefly while the page is loading and then your code will hide it.
If you can't modify the CSS or the HTML for the google object and you're just trying to hide it as soon as possible with javascript and the google object is present in the HTML of your page (not added programmatically), then you can do this:
<body>
other HTML here
<script>
// script that executes right before the /body tag
checkCookie("MyCookie")
</script>
</body>
This will at least not wait for all images to load before hiding it.
I fixed it like this:
Create a css property of display:none; for #google
#google{display:none;}
Then switch around the last portion of code to display only if they don't have the cookie, and to create the cookie.
/** Check if cookie exists else create a new one. **/
function checkCookie(name) {
if (readCookie(name)) {
}
else document.getElementById('google').style.display = "inline";
document.getElementById('google').style.visibility = "visibility";
createCookie(name,"cookie 4 the day",1);
In case anyone runs into this problem. Worked great for me.

Class of ID Change based on URL - URL Based Image Swap -

What I'm trying to achieve:
Based on URL (ie., foo.com/item1), the div element "logoswap" receives a different class.
The following is the code I put together but it seems completely wrong. I'm not a JS pro by any means, XHTML/CSS is more my speed (some PHP)... I cannot use PHP, even if it is possible in PHP (and I know it is because I have a PHP version of what I need done already, but I can't call the PHP properly.
I'm really just trying to get a different logo to show up based on the directory/url... It doesn't have to be a background element called in by the CSS class necessarily, I just need a different image to load based on the aforementioned url variable...
$(function() {
var url = location.pathname;
if(url.indexOf('item1') > -1) {
document.getElementById("logoswap").className += " class1";
}
elseif(url.indexOf('item2') > -1) {
document.getElementById("logoswap").className += "class2";
}
elseif(url.indexOf('item3') > -1) {
document.getElementById("logoswap").className += "class3";
}
elseif(url.indexOf('item4') > -1) {
document.getElementById("logoswap").className += "class4";
}
elseif(url.indexOf('item5') > -1) {
document.getElementById("logoswap").className += "class5";
}
else {
document.getElementById("logoswap").className += "class1";
}
});
That's what I have... Ugly I'm sure.
That's why I'm here though, I definitely need some help.
Assigning CSS Class By URL Pathname
A jsfiddle has been setup for
this solution.
Here is a case for using numeric expressions if they are available. This does not apply to the above question.
$(function() {
var rgx = /item(\d+)$/,
url = location.pathname,
id = (rgx.test(url)) ? url.match(rgx)[1] : '1';
$("#logoswap").addClass("class" + id);
});
UPDATE:
In light of the new details you may need an array of values, these should be derived from or exactly equal to the class names you intend to use.
$(function(){
// my favorite way to make string arrays.
var matches = "brand1 brand2 brand3".split(" "),
url = location.pathname.match(/\w+$/)[0], // get the last item
id = matches.indexOf(url),
className = matches[(id > -1) ? id : 0];
$("#logoswap").addClass(className);
});
To make this work you will need a few things in place. I will assume that the paths will end in a number as we have outlined here. The default ends with 1. You will need the images to be accessible. You need to define the styles for each possibility.
CSS Setup
#logoswap {
height : 200px;
width : 200px;
}
.class1 {
background-image : url(/path/to/default.jpg);
}
.class2 {
background-image : url(/path/to/second.jpg);
}
.brand1 {
background-image : url(/path/to/brand/1/logo.jpg);
}
...
Without jQuery
if you do not have jQuery in your code you may need to use window.onload.
(function(){
var old = window.onload;
window.onload = function(){
old();
var r = /item(\d+)$/,
url = location.pathname,
id = (r.test(url)) ? url.match(r)[1] : '1';
document.getElementById('logoswap').className += "class" + id;
};
})()
I just want to take a moment here to
encourage anyone who is doing this
type of code to get used to Regular
Expressions and learn them. They are
far and away the most frequently used
cross language part of my development
arsenal.
There's nothing that wrong with what you have. You could tidy it up with something like below.
$(function() {
var url = location.pathname;
var logo = document.getElementById("logoswap");
var i = 6;
logo.className = "class1";
while(i--)
{
if(url.indexOf("item" + i) > -1) {
logo.className = "class" + i;
}
}
});
Hope this helps.
Using just HTML/CSS, you could add (or append via javascript) an id to the body of the page:
<body id="item1">
Then in your CSS, create a selector:
#item1 #logoswap {
// class1 CSS
}

Categories

Resources