preventDefault, make changes and continue routine - javascript

I have a small site with a script that runs a query with mysql and returns me some data, including domains. These domains are generated html links and I want to change in javascript, since I can not access the part of php, but yes to the javascript and css code.
I just want you the code is run when the click event is triggered on a link. I tried to stop the execution by default and make a change, but my code does not open the page. If I remove preventDefault only works in firefox, but I have not chrome. (window.open not use, I want to change the original link).
var domains = document.getElementsByClassName("domain");
for(var x = 0; x < domains.length; x++){
if(domains[x].addEventListener) {
domains[x].addEventListener("click", changeLink, "false");
} else if(domains[x].attachEvent) {
domains[x].attachEvent("onclick", changeLink);
}
}
function changeLink(evt){
var urlOriginal = this.href;
// If I remove preventDefault, the function runs correctly on firefox but not in chrome
evt.preventDefault();
if(urlOriginal != 'http://google.com') {
urlOriginal = urlOriginal.replace(/http:\/\//g, '');
evt.stopPropagation();
this.href = 'http://intodns.com/' + urlOriginal;
console.log('Okay !');
}
return true;
}
I tried several changes but none is running, not really the case.
Does anyone know the cause of malfunction? How I can fix it without window.open?
Thanks

try stopPropagation instead
http://api.jquery.com/event.stoppropagation/ - read more about it

If I understand correctly, you want to redirect the user to a different link, instead of the one that is set in the href attribute.
Once the click is made, nothing will happen if you change the href attribute of the element. What you are looking for is redirecting the user, and this is made possible by modifying the location object which resides on window.
Instead of this line:
this.href = 'http://intodns.com/' + urlOriginal;
Try this:
window.location = 'http://intodns.com/' + urlOriginal;

Related

Trying to disable the browser's back button

I've written two HTML files:
Login.html
Next Page
Home.html`
<html>
<body>
<a href = >Login.html>>Prev Page</a>
</body>
<script type = "text/javascript" >
history.pushState("anything", "", "#1");
window.onhashchange = function (event) {
window.location.hash = "a";
};
</script>
</html>
`
I'm trying to disable browser's back button. If i execute this code on chrome it doesn't disable the back button but if i run history.state command in console of Home.html page and then i click the back button, then it remains on same page(works as expected). Why so?
FOA, Thanks everyone for your answers.
Finally below code gave me the solution:
history.pushState(null, null, window.location.href);
history.back();
window.onpopstate = () => history.forward();
You can't disable the browser's back button. If you could, that would be a security hazard and the browser vendors would most likely seek to fix it.
It is generally a bad idea overriding the default behavior of web browser. Client side script does not have the sufficient privilege to do this for security reason.
There are few similar questions asked as well,
How can I prevent the backspace key from navigating back?
How to prevent browser's default history back action for backspace button with JavaScript?
You can-not actually disable browser back button. However you can do magic using your logic to prevent user from navigating back which will create an impression like it is disabled. Here is how, check out the following snippet.
(function (global) {
if(typeof (global) === "undefined") {
throw new Error("window is undefined");
}
var _hash = "!";
var noBackPlease = function () {
global.location.href += "#";
// making sure we have the fruit available for juice (^__^)
global.setTimeout(function () {
global.location.href += "!";
}, 50);
};
global.onhashchange = function () {
if (global.location.hash !== _hash) {
global.location.hash = _hash;
}
};
global.onload = function () {
noBackPlease();
// disables backspace on page except on input fields and textarea..
document.body.onkeydown = function (e) {
var elm = e.target.nodeName.toLowerCase();
if (e.which === 8 && (elm !== 'input' && elm !== 'textarea')) {
e.preventDefault();
}
// stopping event bubbling up the DOM tree..
e.stopPropagation();
};
}
})(window);
This is in pure JavaScript so it would work in most of the browsers. It would also disable backspace key but key will work normally inside input fields and textarea.
Recommended Setup:
Place this snippet in a separate script and include it on a page where you want this behavior. In current setup it will execute onload event of DOM which is the ideal entry point for this code.
Working Demo link-> http://output.jsbin.com/yaqaho
The HTML5 History API gives developers the ability to modify a website's URL without a full page refresh. This is particularly useful for loading portions of a page with JavaScript, such that the content is significantly different and warrants a new URL.
You can check this link it may helpful
https://css-tricks.com/using-the-html5-history-api/

Html anchor linking and hashbang, simple solution?

I have in http://www.g3eo.com/#!/page_About the following in line 96:
<li>Side scan sonar surveys</li>
and need to create an anchor to go to line 180:
<li id="sidescan"><strong>Side scan sonar surveys</strong></li>
I understand that to get this working I would need to do:
<li>Side scan sonar surveys</li>
<li id="sidescan"><a name="sss"><strong>Side scan sonar surveys</strong></a></li>
But this does nothing. I was wondering if the problem is the hashbang in #!/page_Services, without it the web page stops working properly.
Something like this will work:
// Run the code on page load. Change this to whatever your page callback is
window.addEventListener('load', function(e)
{
// Find any of the anchors that have a hash link.
// Change document to whatever the container is for your new elements
as = document.querySelectorAll('a[href^="#"]');
as.forEach(function(a)
{
a.addEventListener('click', function(e)
{
// This stops the hash being added to the URL on click
e.preventDefault();
// Find the hash and the target element (based on ID)
var hash = e.target.href.split('#')[1];
var targetEl = document.getElementById(hash);
// Scroll the window to the target elements offsetTop
window.scrollTo(0, targetEl.offsetTop);
});
});
});
But you'll need to run this code after the content that you want to use is loaded (rather than on page load).
Basically, this simulates hash linking without adding the hash to the url. See here for a working version - https://plnkr.co/edit/mubdlfjuFTgLeYq6ZpCR?p=preview
I started working on a solution very similar to #Liam Egan's, which is good, but I thought "What if someone wants to share a link to an anchor tag? I'll just try using both a hashbang and an anchor hash in the URL!".
After multiple tests, as it turns out, it's really hard to maintain, especially if you use an external library which uses the hash. It will break, so I abandoned that idea.
Here is a solution for clicks on links, which I tested on your website:
$(function(){
$('a[href^="#"]').click(function(e){
// Get the hashes in link
var h = this.href.split('#');
// If the first hash is not a hashbang or if there are several hashes
if(h[1].indexOf('!') !== 0 || h.length > 2) {
// Prevent default behavior of the link so it does not break the site
e.preventDefault();
// If the first hash is a hashbang (but there are multiple hashes),
// only include the first one in the page URL
if(h[1].indexOf('!') === 0) { window.location.hash = '#' + h[1]; }
// Get the element with the right ID (last hash) and its scrolling container
var el = $('#' + h.pop()), cont = el.closest('div[class^="scroll"]');
// Scroll the scrolling container to that element after a delay,
// because it does not work during the page transition
setTimeout(function() {
cont.scrollTop(0) // Reset it first to get the right position below
.scrollTop( el.position().top );
},500);
}
});
});
I had to adapt it for two reasons:
Not the whole document should scroll, just your wrapping .scroll div
The scrolling won't work during page transition, so it needs a delay
It does not affect links such as #!/page_XXX, and will work with links such as #myID or #!/page_XXX#myID.
Finally, for simplicity, since you are using jQuery, I did too. Place that piece of code anywhere on your page after loading jQuery, and it should work.

ZeroClipboard user script adding in mouse over, working in firefox, but not chrome

I am using zeroclipboard to add a "copy" link to each row in a fairly large list, within a user script. To accomplish that, I using a method similar to the one listed on this page, where the ZeroClipboard.Client() element for each row is created when the user mouses over the row. This is working great in FireFox, but not in Chrome.
Also as a note: I copied the contents of the ZeroClipboard.js file into the user script itself instead of including it in an external file.
Here is the markup that creates the copy button for each element
<span style="color:blue; text-decoration:underline; cursor:pointer" id="copy_'+id+'" class="CopyLink" link="'+url+'" onmouseover="clipboard.add(this)">Copy</span>
Here is the code segment that adds the clipboard's client object:
function main(){
window.clipboard = {
load: function (){
if(!clipboard.initialized){
ZeroClipboard.setMoviePath("http://www.swfcabin.com/swf-files/1343927328.swf");
clipboard.initialized=true;
console.log("Clipboard intialized");
}
},
add: function(element){
clipboard.load();
var clip = new ZeroClipboard.Client();
console.log('Clipboard client loaded: ' + element.id);
clip.glue(element, element.parentNode);
console.log('Clipboard glued: ' + element.id);
clip.setText(element.getAttribute('link'));
console.log('Clipboard text set: ' + element.getAttribute('link'));
clip.addEventListener('complete',function(client,text) {
console.log('Clipboard copied: ' + text);//doesn't fire in chrome
});
clip.addEventListener('load',function(client) {
console.log('Clipboard loaded: ' + element.getAttribute('link'));
});
}
}
//other code in user script including injecting above markup
//as well as contents of ZeroClipboard.js
window.ZeroClipboard = { ... }
}
var script = document.createElement("script");
script.appendChild(document.createTextNode('('+main+')()'));
(document.head || document.body || document.documentElement).appendChild(script);
In this block, every console.log fires in FireFox when I mouse over and click the copy span, but in chrome, all except the 'complete' listener fire. I was able to verify that ZeroClipboard is working in my Chrome by using the example on this page. I am also able to verify that the flash object is being added to the page in the correct location, but it is simply not responding to a click.
Since the zeroclipboard code is no longer being maintained according to the site, I'm hoping someone out there can help me out. I'm thinking there is possibly some issue with dynamically adding the embedded flash objects in chrome on mouseover, or perhaps some difference between user scripts in chrome vs firefox with greasemonkey? Any help would be greatly appreciated, thanks
I'm not sure the reason behind it but I have been running into this on Chrome as well. I had two zeroclipboard implementations, one that was visible on page load, and one that was only visible when the user opened a dialog. The one that was visible on page load worked as expected, but the other one didn't. In order to "solve" the issue, I had to render the zeroclipboard link, set its absolute position to be off the screen (-500 px), then add some javascript to move the link into place when the dialog opens. This is an ugly solution but I think is the only way to get it to work in Chrome. Your case is particularly hairy since you have lots of dynamic zeroclipboards on your page whereas I only had one, but it seems to me that there's no reason this won't work for you.
<!-- <script type="text/javascript" src="http://davidwalsh.name/demo/ZeroClipboard.js"></script> -->
function copyText(fieldName,buttonName){
var fieldNameTemp =fieldName;
var buttonNameTemp =buttonName;
var val = "";
try{
val = navigator.userAgent.toLowerCase();
}catch(e){}
var swfurl = "js/ZeroClipboard.swf";
setTimeout(function () {
ZeroClipboard.setMoviePath(swfurl);
var clip = new ZeroClipboard.Client();
clip.addEventListener('mousedown', function () {
clip.setText(document.getElementById(fieldNameTemp).value);
});
clip.addEventListener('complete', function (client, text) {
try{
if(val.indexOf("opera") > -1 || val.indexOf("msie") > -1 || val.indexOf("safari") > -1 || val.indexOf("chrome") > -1){
alert('Your text has been copied');
}
}catch(e){
alert('Please alert not use on fireFox');
}
});
clip.glue(buttonNameTemp);
}, 2000);
}

Retrieve current focused/mouse-overed hyperlink URL

I'm working on an extension that I need to find a way to catch the current focused link.
When we hit TAB Key, or mouse over a hyperlink, we can see in the status bar (right side of the address bar for firefox 4+) the URL of that link has been shown.
How do you capture this URL with Javascript in Add-on online builder? how do I store it into a variable and whenever the focused link is changed, the variable value will be updated accordingly? I searched internet for hours and so far found this function called Document.activeElement.href ?? But I'm not sure that's what I need and if it is, how do I use it?
Please help!
Thanks !!!
This should do the trick:
<html><body>
link 1
link 2
<div id="output"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
<script>
var handler = function() {
jQuery('#output').text( jQuery(this).attr('href') );
};
jQuery('a').focus(handler).mouseover(handler);
</script>
</body></html>
Let me know if you don't want to use jQuery, and I'll re-write my answer.
The variable window.XULBrowserWindow.overLink happens to contain the current hovered URL as shown in the status bar but it doesn't save the actual element being hovered.
http://jsfiddle.net/DmX5j/6/
var links = document.getElementsByTagName('a'),
linkDisplay = document.getElementById('currentLink'),
currentLink;
for(var i =0; i < links.length; i++){
links[i].onfocus = function(){updateLink(this.href)};
links[i].onmouseover = function(){updateLink(this.href)};
}
function updateLink(link){
currentLink = link;
linkDisplay.innerHTML = currentLink;
}
pure JS way. Not sure if this is what you are looking for or not, basically on focus or mouseover the current link is updated.
you will need to put event handlers on all links of the interest, this is quite easy using jQuery, when the event trigger you can capture the href attribute and process accordingly

Setting Focus to an iFrame in IE

There is a tree menu in my application and on click of the menu items, it loads a url in a iFrame. I like to set the focus in an element of the page loaded in the iFrame.
I'm using this code, and it works perfectly in all the browsers except IE:
var myIFrame = $("#iframeName");
myIFrame.focus();
myIFrame.contents().find('#inputName').focus();
I have tried all different options like using setTimeout, but no chance.
After the page loads, when I hit the tab key, it goes to the second input, which means it's been on the first input, but it doesn't show the cursor!
I am using ExtJS and the ManagedIFrame plugin.
Any help is appreciated.
You need to call the focus() method of the iframe's window object, not the iframe element. I'm no expert in either jQuery or ExtJS, so my example below uses neither.
function focusIframe(iframeEl) {
if (iframeEl.contentWindow) {
iframeEl.contentWindow.focus();
} else if (iframeEl.contentDocument && iframeEl.contentDocument.documentElement) {
// For old versions of Safari
iframeEl.contentDocument.documentElement.focus();
}
}
Is the iFrame visible onload, or shown later? The elements are created in different order which is the basis of the setTimeout approach. Did you try a high value wait time on a set timeout?
Try something like at least a half second to test...IE tends to do things in a different order, so a high timeout may be needed to get it not to fire until render/paint finishes:
$(function(){
setTimeout(function() {
var myIFrame = $("#iframeName");
myIFrame.focus();
myIFrame.contents().find('#inputName').focus();
}, 500);
});
Difficult to troubleshoot without a working example, but you might try hiding and showing the input as well, to force IE to redraw the element.
Something like:
var myIFrame = $("#iframeName");
myIFrame.focus();
myIFrame.contents().find('#inputName').hide();
var x = 1;
myIFrame.contents().find('#inputName').show().focus();
This might jolt IE into displaying the cursor.
I could get IE to focus an input field in an iframe with:
iframe.focus();
var input = iframe...
input.focus();
iframe.contentWindow.document.body.focus();
input.focus();

Categories

Resources