disable href after 1 click on html? - javascript

I want the href to be disabled after 1 click, can it be done using javascript or jquery?
Please help.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns ="http://www.w3.org 1999 xhtml" xml :lang="en">
<head>
<style>
a:link{
color:#1DAAA1;
}
a:visited{
color:green;
}
a:hover{
background: #ff0000;
color: #FFF;
}
</style>
</head>
<body>
<table width="500" align="center" border="5px solid">
<tr align="center" >
<td> Google </td>
<td> Yahoo </td>
<td> Bing </td>
<td> Wikipedia </td>
<td> Facebook </td>
</tr>
</table>
</body>
</html>

Pure javascript solution:
<script>
function clickAndDisable(link) {
// disable subsequent clicks
link.onclick = function(event) {
event.preventDefault();
}
}
</script>
Click here

This is simpler approach using jQuery that prevents links double clicking: no onclick attributes, id isn't required, no href removing.
$("a").click(function (event) {
if ($(this).hasClass("disabled")) {
event.preventDefault();
}
$(this).addClass("disabled");
});
Tip: you can use any selector (like button, input[type='submit'], etc.) and it will work.

just try this....
a:visited {
color:green;
pointer-events: none;
cursor: default;
}

Pure JavaScript solution to allow user to follow the URL only once:
<a id="elementId"
href="www.example.com"
onclick="setTimeout(function(){document.getElementById('elementId').removeAttribute('href');}, 1);"
>Clik and forget</a>
Once clicked, this will remove the href attribute (with 1 ms wait to allow the original action to start) making the link silent. Similar as suggested by Dineshkani, but the original answer caused action to not to start at all on some browsers.

this time i tried it with Javascript... hope it will help u:) just call the below function in "onclick()" of the required href tags...
​function check(link) {
if (link.className != "visited") {
//alert("new");
link.className = "visited";
return true;
}
//alert("old");
return false;
}​​
like ​link here​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
and see demo here

You can do with jquery
<a href='http://somepage.com' id='get' onlick='$("#"+this.id).attr("href","")'>Something to be go </a>
Or with the javascript
<a href='http://somepage.com' id='get' onlick='document.getElementById(this.id).removeAttribute("href");'>Something to be go </a>

Based on Ayyappan Sekar's answer, I have just done something very similar using jQuery:
$('#yourId').click(function (e) {
if(!$(this).hasClass('visited'))
{
$(this).addClass('visited')
return true;
}
else
{
$(this).removeAttr("href"); // optional
// some other code here
return false;
}
});

duplicate the same div in html and css, the duplicated one must be below the original one using: z-index=-1 or/and position:absolute.
make the original div onclick="HideMe(this)"
JS:
<script type="text/javascript">
function HideMe(element){
element.style.display='none';
}
</script>
it might be not the best way, but 100% goal achievable.

I want to leave here an example that works with Knockout.js that I used with IFrame, but as IFrame doesnt work with local files, I made this example with divs.
When you click the link, the function is called, as you can see with the alert()commented inside, but when you dial something in the input dialog and click again the link, the div is not updated by the Knockout.js, only if you click the other link that calls the same function but with diferent parameter.
<html>
<head>
<script type="text/javascript" src="http://knockoutjs.com/downloads/knockout-3.2.0.js"></script>
</head>
<body>
<div>
Page 2
</div>
<div>
Page 3
</div>
<div data-bind="bindHTML: dados"></div>
<script type="text/javascript">
function myPage2(nPage) {
var cPage = '<div>Pagina 2</div>';
if (nPage == 3) { cPage = '<div>Pagina 3</div>' }
cPage += '<input type="text" id="fname" name="fname">';
//alert('clicked!');
return cPage
}
var viewModel = {
dados : ko.observable()
}
ko.bindingHandlers.bindHTML = {
init: function () {
// Prevent binding on the dynamically-injected HTML (as developers are unlikely to expect that, and it has security implications)
return { 'controlsDescendantBindings': true };
},
update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
// setHtml will unwrap the value if needed
ko.utils.setHtml(element, valueAccessor());
var elementsToAdd = element.children;
for (var i = 0; i < elementsToAdd.length; i++) {
ko.cleanNode(elementsToAdd[i]); //Clean node from Knockout bindings
ko.applyBindings(bindingContext, elementsToAdd[i]);
}
}
};
ko.applyBindings(viewModel);
viewModel.dados(myPage2(2));
function fAlter(nPage) {
viewModel.dados(myPage2(nPage));
}
</script>
</body>
</html>

jQuery solution:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns ="http://www.w3.org 1999 xhtml" xml :lang="en">
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
function check(link) {
$(link).replaceWith($(link).text());
}
</script>
<style>
a:link{
color:#1DAAA1;
}
a:visited{
color:green;
}
a:hover{
background: #ff0000;
color: #FFF;
}
</style>
</head>
<body>
<table width="500" align="center" border="5px solid">
<tr align="center" >
<td> Google </td>
<td> Yahoo </td>
<td> Bing </td>
<td> Wikipedia </td>
</tr>
</table>
</body>
</html>

Related

My JS scrollTo function does not scroll the page

My goal is to have a clickable button/link to scroll to a certain position in a page. I have referenced from this answer by Michael Whinfrey, the code works perfectly on fiddle but not on mine.
This may be a bit messy but I have multiple GridViews in a table, and some td has div and some don't. Also in the code behind I have the following code in Page_load.
Page.MaintainScrollPositionOnPostBack = false;
Below is my aspx page simplified.
<html>
<head>
<script type="text/javascript">
function scrollTo(name) {
ScrollToResolver(document.getElementById(name));
}
function ScrollToResolver(elem) {
var jump = parseInt(elem.getBoundingClientRect().top * .2);
document.body.scrollTop += jump;
document.documentElement.scrollTop += jump;
if (!elem.lastjump || elem.lastjump > Math.abs(jump)) {
elem.lastjump = Math.abs(jump);
setTimeout(function () { ScrollToResolver(elem); }, "100");
} else {
elem.lastjump = null;
}
}
</script>
</head>
<body>
.......some input/textbox......
<button onclick="scrollTo('divDesignation')">TEST</button>
<div>
<table>
<tr>
<td>
<asp:GridView id="gv1" .....>
......the whole table has 6~7 rows of GridView data that is not displaying here.....
<tr>
<td>
<div id="divDesignation" runat="server" style="max-height:600px; overflow-y:auto;">
<asp:GridView id="gvDesignation" ......
</div>
</td>
</tr>
</body>
</html>
I am trying to scroll to the divDesignation when click the button but it simply will not.
Any help is appreciated.

Trying to change a link on button click with javascript

I have three buttons and i want such tha when i click on one button the link on an a tag changes
<a class="payverlink" href="exbronzeregistrationform.php">Continue to registration</a>
<button class="goldpac">Choose Plan</button>
<button class="silverpac">Choose Plan</button>
<button class="bronzepac">Choose Plan</button>
I want such that when i click on one button, it changes the link at .payverlink
I have tried
function bronze()
{
$('.payverlink').href="exbronzeregistrationform.php";
}
function silver()
{
$('.payverlink').href="exsilverregistrationform.php";
}
<button class="silverpac" onclick="silver()">Choose Plan</button>
<button class="bronzepac" onclick="bronze()">Choose Plan</button>
But this changes to bronze function onclick of any of the buttons. Please whats the issue.
You could set your javascript code to trigger the button click and avoid using the onclick into html
$(document).ready(function() {
$("button").on('click', function(){
if ($(this).hasClass('goldpac')) {
window.location="http://..."; /* or exbronzeregistrationform.php for example */
} else if ($(this).hasClass('silverpac')) {
window.location="http://..."; /* or exbronzeregistrationform.php for example */
} else if ($(this).hasClass('bronzepac')) {
window.location="http://..."; /* or exbronzeregistrationform.php for example */
}
});
});
You could add one more line in each case changing the a tag, but ti wont make a huge difference in your actions as it isn't used as you click the buttons.
$("a.payverlink").attr("href", "http://...."); /* or exbronzeregistrationform.php for example */
So, you could just remove the 'href' as you contantly will change the url from js.
Use attr or prop, attr stands for attribute and prop for property!
$(
function(){
$('#google').attr('href', 'https://duckduckgo.com/');
//or use prop
$('#duckduckgo').prop('href', 'https://bing.com')
}
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS Learning</title>
</head>
<body>
<h1 class="header"></h1>
<a id="google" href="https://google.com/">google is down!</a>
<br>
<a id="duckduckgo" href="https://duckduckgo.com/">I'm slow...</a>
</body>
</html>
I suspect that both functions are failing, since there is no such property href on JQuery object.
Use this approach instead:
$('.payverlink').prop("href","exbronzeregistrationform.php");
Have you try .prop() method of jQuery hopefully it works .
function bronze()
{
$('.payverlink').prop('href','exbronzeregistrationform.php');
}
function silver()
{
$('.payverlink').prop('href','exsilverregistrationform.php');
}
You can use the .attr function:
function bronze(){
changeLink('exbronzeregistrationform');
}
function silver(){
changeLink('exsilverregistrationform.php');
}
function changeLink(url){
$('.payverlink').attr('href',url);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="payverlink" href="exbronzeregistrationform.php">Continue to registration</a>
<button class="silverpac" onclick="silver()">Choose Plan silverpac</button>
<button class="bronzepac" onclick="bronze()">Choose Plan bronzepac</button>
function bronze()
{
$('.payverlink').attr("href","exbronzeregistrationform.php");
}
function silver()
{
$('.payverlink').attr("href","exsilverregistrationform.php");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="payverlink" href="exbronzeregistrationform.php">Continue to registration</a>
<button class="goldpac">Choose Plan</button>
<button class="silverpac" onclick="silver()">Choose Plan</button>
<button class="bronzepac" onclick="bronze()">Choose Plan</button>
You can try this. it will helps you. :)

html multiselect images

I printed to the screen 16 icons (little pictures).
Now I want to be able to select icons,
and when I press a button the selected icons ids will be sent in a form.
I saw in the net only checkboxes and lists multiselect,
what's the best way to do this?
(I'm pretty new to web design)
thanks ahead!
Although jQuery isn't in your tags, you should introduce yourself to jQuery. It'll make your life easier, for what you're trying to do. Here is the basic steps both if you use jQuery and if use just Javascript:
With jQuery
Give all your icons a class and each one a unique id:
<img src='icon1.png' data-iconID=2233 class='myIcons' />).
Then bind that class to a click event
$('.myIcons').bind('click', function() {
$(this).toggleClass('selectIcon');
});
Attach form submit function to onsubmit:
<form ... onsubmit="submitForm();">
Build submitForm function:
function submitForm() {
var csvIconIds = '';
$.each($('.myIcons.selectIcon'), function (index, value) {
csvIconIds += $(value).attr('data-iconID');
});
//submit scvIconIds here along with other form data (ajax?)
}
With Javascript
Similar as above but way more complicated...
To toggle classes see this thread: How to add/remove a class in JavaScript?
To getting attributes by class see this site: http://www.actiononline.biz/web/code/how-to-getelementsbyclass-in-javascript-the-code/
This could be a way using just plain Javascript or jQuery. I prefer the jQuery version, since it separates the click handler from the markup, instead of using inline onclick handlers, which are in general discouraged.
What this does is use an input element array, which you can create by adding [] to the element name. This same technique can be used on SELECTs and other elements, since it signals to the server that an array has been submitted, as opposed to value known by a single key.
<html>
<head>
<style type="text/css">
div img {
cursor: pointer;
border: 1px solid #f00;
}
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js"></script>
<script>
function setFormImage(id) {
if (id != '' && !document.getElementById('input_'+id)) {
var img = document.createElement('input');
img.type = 'text';
img.id = 'input_'+id;
img.name = 'images[]';
img.value = id;
document.imageSubmit.appendChild(img);
}
}
$(document).ready(function(){
$('#jqueryimages img').click(function(){
setFormImage(this.id);
});
});
</script>
</head>
<body>
<pre><?php
if (count($_GET['images'])) {
print_r($_GET['images']);
}
?></pre>
<div style="float: left; width: 49%;">
<h1>Plain ol' HTML</h1>
1. <img src="http://www.gravatar.com/avatar/e1122386990776c6c39a08e9f5fe5648?s=128&d=identicon&r=PG" id="img-1" onclick="setFormImage(this.id)"/>
<br/>
2. <img src="http://www.gravatar.com/avatar/e1122386990776c6c39a08e9f5fe5648?s=128&d=identicon&r=PG" id="img-2" onclick="setFormImage(this.id)"/>
<br/>
3. <img src="http://www.gravatar.com/avatar/e1122386990776c6c39a08e9f5fe5648?s=128&d=identicon&r=PG" id="img-3" onclick="setFormImage(this.id)"/>
<br/>
4. <img src="http://www.gravatar.com/avatar/e1122386990776c6c39a08e9f5fe5648?s=128&d=identicon&r=PG" id="img-4" onclick="setFormImage(this.id)"/>
</div>
<div id="jqueryimages" style="float: left; width: 49%;">
<h1>jQuery</h1>
5. <img src="http://www.gravatar.com/avatar/e1122386990776c6c39a08e9f5fe5648?s=128&d=identicon&r=PG" id="img-5"/>
<br/>
6. <img src="http://www.gravatar.com/avatar/e1122386990776c6c39a08e9f5fe5648?s=128&d=identicon&r=PG" id="img-6"/>
<br/>
7. <img src="http://www.gravatar.com/avatar/e1122386990776c6c39a08e9f5fe5648?s=128&d=identicon&r=PG" id="img-7"/>
<br/>
8. <img src="http://www.gravatar.com/avatar/e1122386990776c6c39a08e9f5fe5648?s=128&d=identicon&r=PG" id="img-8"/>
</div>
<h1>Form Submit</h1>
<form name="imageSubmit" method="get">
<input type="submit" value="View Selected"/>
</form>
</body>
</html>
try this
var idArray = [];
$("#container-id img").each(function(index,value){
idArray.push($(value).attr("id"));
});
//do anything with the array

In my case, How to highlight table row when mouseover?

In my index.html page, I have an empty table defined as following:
<body>
...
<table width="500" border="0" cellpadding="1" cellspacing="0" class="mytable">
<tr></tr>
</table>
<script src="my.js"></script>
</body>
As you saw above, there is an JavaScript file my.js is included.
my.js(which is used to update the table row):
var items = ARRAY_OF_OBJECTS_FROM_SERVER; //e.g. items=[{'John', '023567'},{'Bill', '055534'},...];
//Each object element in the "items" array contain "name" and "phone" attribute.
var mytable = $('.mytable tr:first');
for(var i=0; i<items.length; i++){
var obj = items[i];
mytable.after("<tr>");
mytable.after("<td> </td>");
mytable.after(" <td>"+obj.name+"</td>");
mytable.after("<td>"+obj.phone+"</td>");
mytable.after("</tr>");
}
I successfully get the dynamical table working, but when I try to add mouse hover effect on each row, I just failed. What I tried is by using CSS:
.mytable tr:hover
{
background-color: #632a2a;
color: #fff;
}
I would like the mouse hover with color highlight effect to be working on IE 7+, firefox and chrome, what is the correct way to implement the table row mouse hover effect in my case??
----EDIT----
Here is my index.html page:
index.html
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="https://getfirebug.com/firebug-lite.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>my test</title>
<link href="mystyle.css" rel="stylesheet" type="text/css" media="screen" />
</head>
<body>
<table width="500" border="0" cellpadding="1" cellspacing="0" class="mytable">
<tr>
</tr>
</table>
<script src="my.js"></script>
</body>
</html>
--SOLUTION----
#manji 's solution solved my problem. That's change in JavaScript to use append instead of after inside for loop. Then, the CSS way of highlighting row is working.
You are writing the <td> outside of <tr> with this:
mytable.after("<tr>");
mytable.after("<td> </td>");
mytable.after(" <td>"+obj.name+"</td>");
mytable.after("<td>"+obj.phone+"</td>");
mytable.after("</tr>");
For example, first one will add a <tr> and close it, then 3 closed <td>s before the <tr> and the last one is incorrect and will have no effect.
Try it this way and it will work:
mytable.after("<tr>"
+"<td> </td>"
+"<td>"+obj.name+"</td>"
+"<td>"+obj.phone+"</td>"
+"</tr>");
and it's better to use .append() (it will add the objects in their list order):
var mytable = $('.mytable'); // mytable selector is changed to select the table
// you can remove the empty <tr>
for(var i=0; i<items.length; i++){
var obj = items[i];
mytable.append("<tr>"
+"<td> </td>"
+"<td>"+obj.name+"</td>"
+"<td>"+obj.phone+"</td>"
+"</tr>");
Try the following:
.mytable tr:hover td
{
background-color: #632a2a;
color: #fff;
}
Given your list of browser support, CSS is the proper solution. It's important to note that the cells (<td>) cover the row (<tr>). So it's their background that you want to modify.
You're best bet is to use jquery's hover: Click Here
IE 7 did not have hover support on elements other than anchor tags. (or maybe that was just 6) either way, since you are using jquery already you can get your hover effect done easily.
$("tr").hover(
function () {
$(this).addClass('hover_class');
},
function () {
$(this).removeClass('hover_class');
}
);
Note: IE 7 will only allow :hover if you are running in HTML 4.01 STRICT for your doctype. Otherwise you need to use javascript to accomplish what you are looking to do.
If you cannot get the css solution to work use a delegate function to handle the dynamic rows.
$("table.mytable").delegate("tr", "hover", function(){
$(this).toggleClass("hover");
});
jQuery:
$('.mytable tr').hover(function() {
$(this).addClass('active');
}, function() {
$(this).removeClass('active');
});
CSS:
.mytable tr.active td
{
background-color: #632a2a;
color: #fff;
}
Check out the working example: http://jsfiddle.net/JpJFC/
Use jquery delegate method which is the best way to do it from performance point of view.
$(".mytable").delegate("tr", "mouseover", function(e) {
$(this).addClass('mouseoverClass');
});
$(".mytable").delegate("tr", "mouseout", function(e) {
$(this).removeClass('mouseoverClass');
});

javascript highlight

i try to make the div color changed when click or focus on textbox so i do this js function but it change the textbox color not its div
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>test</title>
<style type="text/css">
/* This is the CSS class to use when no focus is on the input control */
.input_text
{
border:1px solid #c0c0c0;
padding:4px;
font-size:14px;
color:#000000;
background-color:#ffffff;
}
/* This is the CSS class to use when the control has focus */
.input_text:focus, input.input_text_focus
{
border-color:#646464;
background-color:#ffffc0;
}
</style>
<script type="text/javascript">
// creates a function to set the css class name of input controls when they
// receive or lose focus.
setAspnetTextFocus = function() {
// CSS class name to use when no focus is on the input control
var classBlur = 'input_text';
// CSS class name to use when the input control has focus
var classFocus = 'input_text_focus';
// get all of the input tags on the page
var inputElements = document.getElementsByTagName('input');
for (var i = 0; i < inputElements.length; i++) {
inputElements[i].onfocus = function() {
if (this.className == 'input_text') {
this.className += ' ' + classFocus;
}
}
// add the onblur event and set it to remove the on focused CSS class when it loses focus
inputElements[i].onblur = function() {
this.className = this.className.replace(new RegExp(' ' + classFocus + '\\b'), '');
}
}
}
// attach this event on load of the page
if (window.attachEvent) window.attachEvent('onload', setAspnetTextFocus);
</script>
</head>
<body>
<div class="input_text" >
<input type="text" id="TextBox1" class="input_text" />
</div>
</body>
</html>
any ideas?
To change the text select color you just need CSS. You wont be able to do it with JavaScript except with not so pretty hacks (you'd need to draw a rectangle on top/below the words on select...)
With CSS tho you just need to do (i believe):
#TextBox1::selection {
background: #ffb7b7; /* Safari */
}
#TextBox1::-moz-selection {
background: #ffb7b7; /* Firefox */
}
Source: http://css-tricks.com/overriding-the-default-text-selection-color-with-css/
Just a side note tho in case you care, this is NOT W3C validated CSS.
here is a jsfiddle using JQuery that will do what I think you are asking for: http://jsfiddle.net/pthurlow/GG6Te/
here it is in plain vanilla JS: http://jsfiddle.net/FSZZU/
EDIT code from jsfiddle:
html
<div class="input_text">
<input type="text" id="TextBox1" class="input_text" />
</div>
script
document.getElementById('TextBox1').onfocus = function() {
this.parentNode.className = 'input_text focus_text';
};
document.getElementById('TextBox1').onblur = function() {
this.parentNode.className = 'input_text';
};

Categories