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

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....

Related

How to save custom style rule to LocalStorage?

Button works, but after refreshing the page, the rule is gone.
My code:
// Create the <style> tag
var style = document.createElement("style");
// WebKit hack :(
style.appendChild(document.createTextNode(""));
// Add the <style> element to the page
document.head.appendChild(style);
return style.sheet;
})();
// Button
let spaces = document.getElementById("spaces");
spaces.onclick = () => {
sheet.insertRule(".navbar {letter-spacing: 3px !important;}", 0);
};
You can do it like this:
localStorage.setItem("your item name or id goes here", "value goes here");
So for what you want it could be like this:
localStorage.setItem("size", "15px");
Then you have to get it when the window loads:
window.onload = function(){
var nav = document.getElementById(navbar);
var finalSize = localStorage.getItem('size');
nav.style.letterSpacing = finalSize;
}
Also, give your navbar or element and ID of "navbar".
Also, there is no need to create a style tag. You can do that with style
in javascript.
Shouldn't that be the normal behavior, refreshing the page should reset it to the initial state?
If you want to use LocalStorage for saving the style rules, you can
// Button
let spaces = document.getElementById("spaces");
spaces.onclick = () => {
sheet.insertRule(".navbar {letter-spacing: 3px !important;}", 0);
localStorage.setItem("addNavbarRule", true)
};
// on page load
window.onload = function(){
if (localStorage.getItem("addNavbarRule")){
sheet.insertRule(".navbar {letter-spacing: 3px !important;}", 0);
}
}

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.

Changing Attribute with Javascript-Header Problems

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 {
...
}

Detecting Clicks on DIV Elements Containing Javascript?

How can you detect clicks on javascript which is fired from a <DIV>?
For example I have 3 adSense ads in 3 different <DIV>s on a page, and I want to detect and trigger an operation when an ad is clicked.
It is easy to detect clicks on<DIV> when it is empty, or with any other element; but how to detect clicks on adSense ad (code)?
As far as I'm aware, Adsense ads are loaded in an iframe element so accessing them would be violating the same origin policy. This means you can't detect clicks in an iframe pointing to an external URL, so it can't be done.
are you using any frameworks like jQuery? if so, you could add a click handler to a child of a div:
targetElement = $("#yourDivId").children()[0]
$(targetElement).click(function(){
alert("target element was clicked");
});
If I would really need to achieve something like this, I would cheat a bit with the user.
Instead of trying to get click on iframe, make an overlay div and place it above iframe. Attach click event to it, and when div is clicked, hide it.
It will give the user feeling that he clicked on link, but it did not worked correctly. The second time he clicks it will already worked, cause overlay is hidden.
An example code (just for explanation purpose):
<html>
<style>
.test {
position : absolute;
top : 0;
left : 0;
width : 300;
height : 300;
z-index : 999;
filter : alpha(opacity = 0);
opacity : 0;
background-color:black;
}
</style>
<script>
function start(){
var div = document.getElementById("target");
var source = document.createElement("div");
source.className = "test";
document.body.appendChild(source);
var style = source.style;
var div2 = document.createElement("div");
document.body.appendChild(div2);
source.onclick = function(e){
style.display = "none";
div.onmouseout = function(){
div2.innerHTML = "mouseout";
style.display = "";
div.onmouseout = null;
}
div2.innerHTML = "clicked";
}
}
</script>
<body onload="start()">
<div id="target">
<iframe src="http://mail.ru" style="width:300;height:300"></iframe>
</div>
</div>
</html>

Categories

Resources