How do i make a div/iframe clickable only once - html

The title says it all : How do i make a div/iframe clickable only once
Im stuck with this for a long time,so I decided to ask for a little help.
Please,if you wanna help,put the whole script in here,not just a part of it so I get confused.
Thank you.

This is not very clear question though and it has no tags, but i try..
Assuming that you are using javascript. You can add counter variabel and check it every time you run the event.
window.load = function() {
var count = 0;
document.getElementById('div_or_iframe').onclick = function() {
if(count == 0) { // check if counter is 0
return true; // continue
count++; // update counter by +1
}
else { // if counter is 0 > clicking anything doesn't work
return false; // prevent action
}
}
}

I think that #aksu's answer is much easier, but I got it to work with classes and jquery. This will allow you to have several elements on your page be clickable only once.
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
function someFunction(obj) {
if ($(obj).hasClass("clickable")) {
// perform the code you want
alert("Function will be performed");
// make not clickable
$(obj).removeClass("clickable");
} else {
alert("Already Clicked");
}
}
</script>
</head>
<body>
<div class="clickable" onclick="someFunction(this)">CLICK HERE</span>
</body>
</html>

Related

Angular does not update UI for keyboard event

I want to update page for keyboard event.
I wired the keyboard event through $window.document.onkeydown. (I know this is not good but it is supposed to work)
However, I find that the page is not updating even the model is changed!
Where am I missing ?
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script>
function Main ($scope, $window) {
$scope.keyCode = 0;
$window.document.onkeydown = function (event) {
$scope.keyCode = event.keyCode;
console.log($scope.keyCode); //the model is changed here
};
}
</script>
</head>
<body ng-app>
<div ng-controller="Main">
{{keyCode}}
</div>
<script type="text/javascript" src="bower_components/angular/angular.js"></script>
</body>
</html>
---Edit---
Here is the code snippet you can try
http://plnkr.co/edit/DFUfHzQPla031IEDdCo3?p=preview
Whenever you want to execute an expression that is outside Angular's scope you need to let Angular know that a change has been made so it can perform a proper digest cycle. You can do this using the $scope.$apply() method. So your example becomes:
function Main ($scope, $window) {
$scope.keyCode = 0;
$window.document.onkeydown = function (event) {
$scope.$apply(function () {
$scope.keyCode = event.keyCode;
console.log($scope.keyCode);
});
};
}
Please see updated plunker here

Basic toggle for a Chrome Exstension

I cannot believe I am still have basic programming problems... I know the basics, but still have a hard time implementing the logic I think of. Anyways
I am building this basic Chrome Extension that has one JavaScript file and it does work! The only issue is that once I click the icon it is forever on, that is until I remove it. I want to add a basic toggle functionality, but I am having difficulty getting a working prototype. Here is a couple of my ideas:
var toggle == 1; // or true, i.e. clicked
if (functionName() == 1) {
function functionName() {
Do whatever it is when clicked;
blah blah blah;
} else if (functionName() == 0) {
Turn off;
} else {};
}
switch(toggle)
{
case 1:
Do whatever it is when clicked;
blah blah blah;
break;
case 2:
Turn off;
break;
default:
error;
break;
}
If both if statement and switch statement had a different order, say case 1 and 2 were swapped, I do not think it would be a difference. I do not think a switch statement would be the best way because there is no more than two options, on or off.
What about a while loop to change the conditions of the extension? I do know the modulo operator, and code could be written like:
1 % 2 = False,
2 % 2 = True,
3 % 2 = False, etc
Then a basic if-statement could work....
something like:
var i = 1;
while (i % 2 == 1) {
Do whatever it is when clicked;
blah blah blah;
i++;
}
Does anybody have an idea of the best way to do this? I have played with the jQuery .toggle() event, but I do not think this would make since. I have nothing in the html document and only a JavaScript file. It makes no since loading the library and then using the jQuery selector$("chrome.browserAction.onClicked.addListener(function)") when simple JavaScript can be used. Plus I do not even know if that would be the right selector...
Any help would be great, thanks in advance.
For the record I found the sample extensions useless when it comes to something that should not be complicated.
Thanks!
UPDATE code with my function in background.js:
function trigger() {
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.windows.onFocusChanged.addListener(function(windowId) {
if (windowId != chrome.windows.WINDOW_ID_NONE) {
chrome.tabs.query({ active:true, windowId:windowId }, function(tabs) {
if (tabs.length == 1) {
var tab = tabs[0];
chrome.tabs.reload(tab.id);
}
});
}
});
});
}
var functionOn = false;
chrome.browserAction.onClicked.addListener(function() {
if (functionOn === false) {
document.addEventListener('DOMContentLoaded', function() {
trigger();
});
functionOn = true;
} else if (functionOn === true) {
document.addEventListener('DOMContentLoaded', function() {
//nothing...
});
functionOn = false;
}
The if statement does not work at the moment, my exstension works with this call instead of the if statement at the end:
document.addEventListener('DOMContentLoaded', function() {
trigger();
});
It's hard to give you a super detailed answer without knowing exactly what is supposed to be toggled, but in a nutshell you just need to add something like this to your background script:
var functionOn = false;
chrome.browserAction.onClicked.addListener(function() {
if (functionOn === false) {
doSomething();
functionOn = true;
} else {
functionOn = false;
// Don't do anything.
}
});
By putting the variable "functionOn" in the background page the state is persistent. You may already be aware of this, but to create a background script you simply add this to the manifest file:
"background": {
"scripts": ["background.js"]
},
It's hard to tell what you're trying to do with the toggle, but the doSomething() would basically be whatever action you're trying to perform, whether it's injecting code via a content script or showing a popup, etc.

Unable to show Desktop Notifications using Google Chrome

I followed the instructions as given in Using The Notifications API. Also I faced many problems like the below, because I added the document.querySelector() inside the <head> part:
Uncaught TypeError: Cannot call method 'addEventListener' of null
Now I have the below source, where I am able to Check Notification Support, and Check Notification Permissions links.
Guide me how to bring in notifications in a simpler way. Also, I tried this:
$("#html").click(function() {
if (window.webkitNotifications.checkPermission() == 0) {
createNotificationInstance({ notificationType: 'html' });
} else {
window.webkitNotifications.requestPermission();
}
});
Now I am stuck with this source. I need to generate HTML & Simple Notifications. Am I missing something? Please guide me.
Source:
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>Desktop Notifications</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
function checkNotifications() {
if (window.webkitNotifications)
alert("Notifications are supported!");
else
alert("Notifications are not supported for this Browser/OS version yet.");
}
function createNotificationInstance(options) {
if (window.webkitNotifications.checkPermission() == 0) { // 0 is PERMISSION_ALLOWED
if (options.notificationType == 'simple') {
return window.webkitNotifications.createNotification('icon.png', 'Notification Title', 'Notification content...');
} else if (options.notificationType == 'html') {
return window.webkitNotifications.createHTMLNotification('http://localhost/');
}
} else {
window.webkitNotifications.requestPermission();
}
}
</script>
<style type="text/css">
* {font-family: Verdana, sans-serif;}
body {font-size: 10pt; margin: 0; padding: 0;}
p {margin: 5px;}
a {color: #09f; text-decoration: none;}
a:hover {color: #f00;}
</style>
</head>
<body>
<p><strong>Desktop Notifications</strong></p>
<p>Lets see how the notifications work in this browser.</p>
<p>
Check Notification Support.
Next Check Notification Permissions
and if permissions are not there,
Request Permissions.
Create a
Simple Notification
or
HTML Notification.
</p>
</body>
<script type="text/javascript">
document.querySelector("#html").addEventListener('click', function() {
if (window.webkitNotifications.checkPermission() == 0) {
createNotificationInstance({ notificationType: 'html' });
} else {
window.webkitNotifications.requestPermission();
}
}, false);
document.querySelector("#text").addEventListener('click', function() {
if (window.webkitNotifications.checkPermission() == 0) {
createNotificationInstance({ notificationType: 'simple' });
} else {
window.webkitNotifications.requestPermission();
}
}, false);
</script>
</html>
After creating the notification, you need to call show() on it, so instead of just:
createNotificationInstance({ notificationType: 'simple' });
you need to do:
var n = createNotificationInstance({ notificationType: 'simple' });
n.show();
The other thing is: when doing jQuery code, wrap it inside
$(document).ready(function() {
// ...
// your jQuery code
// ...
});
When doing actions on the DOM with jQuery inside the head, the DOM isn't build yet. $(document).ready waits until the DOM is build and you can savely access and manipulate it.
Here is a working example: http://jsfiddle.net/fkMA4/
BTW: I think HTML notifications are deprecated, see here: http://www.html5rocks.com/en/tutorials/notifications/quick/?redirect_from_locale=de
Notifications with HTML content have been deprecated. Samples and text
have been modified accordingly.

Drag and drop example - HTML5

I'm trying to learn the drag and drop example from the WWWC (here) and I can get the list items to be removed from the original list when dragged away, but not appear in the new list. Any ideas why not? I have tried on Safari 5.1.1, Chrome 15, and Firefox 7.0.1.
<head>
<title>Drag 'N Drop</title>
</head>
<p>What fruits do you like?</p>
<ol ondragstart="dragStartHandler(event)" ondragend="dragEndHandler(event)">
<li draggable="true" data-value="fruit-apple">Apples</li>
<li draggable="true" data-value="fruit-orange">Oranges</li>
<li draggable="true" data-value="fruit-pear">Pears</li>
</ol>
<script>
var internalDNDType = 'text/plain'; // set this to something specific to your site
function dragStartHandler(event) {
if (event.target instanceof HTMLLIElement) {
// use the element's data-value="" attribute as the value to be moving:
event.dataTransfer.setData(internalDNDType, event.target.dataset.value);
event.dataTransfer.effectAllowed = 'move'; // only allow moves
} else {
event.preventDefault(); // don't allow selection to be dragged
}
}
function dragEndHandler(event) {
// remove the dragged element
event.target.parentNode.removeChild(event.target);
}
</script>
<p>Drop your favorite fruits below:</p>
<div dropzone="move s:text/plain" ondrop="dropHandler(event)">
<ol dropzone="move s:text/plain" ondrop="dropHandler(event)">
<!-- don't forget to change the "text/x-example" type to something
specific to your site -->
<li>Bananas</li>
</ol>
</br>
</br>
</br>
</div>
<script>
var internalDNDType = 'text/plain'; // set this to something specific to your site
function dropHandler(event) {
var li = document.createElement('li');
var data = event.dataTransfer.getData(internalDNDType);
if (data == 'fruit-apple') {
li.textContent = 'Apples';
} else if (data == 'fruit-orange') {
li.textContent = 'Oranges';
} else if (data == 'fruit-pear') {
li.textContent = 'Pears';
} else {
li.textContent = 'Unknown Fruit';
}
event.target.appendChild(li);
}
</script>
There are a couple of issues. First, your dropzone needs to cancel the event on drag over:
<ol dropzone="move s:text/plain" ondrop="dropHandler(event)" ondragover="dragOverHandler(event)">
function dragOverHandler(event) {
event.preventDefault();
return false;
}
Second, your dropHandler handler function is going to get fired several times because the drop target, most of the time, is going to be an li element rather than the ol (and possibly also the div, but I ignored that element). So either add code to only handle the event at the ol, or cancel the event in dropHandler with stopPropagation.
Finally, the default action (at least in Firefox, didn't check other browsers) when an item is dropped is to try and navigate to the URL represented by the text/plain value, so you should add some event.preventDefault() in likely places. Here's an updated dropHandler function:
function dropHandler(event) {
var li = document.createElement('li');
var data = event.dataTransfer.getData(internalDNDType);
if (data == 'fruit-apple') {
li.textContent = 'Apples';
} else if (data == 'fruit-orange') {
li.textContent = 'Oranges';
} else if (data == 'fruit-pear') {
li.textContent = 'Pears';
} else {
li.textContent = 'Unknown Fruit';
}
event.target.appendChild(li);
event.stopPropagation();
event.preventDefault();
return false;
}
Here's my updated version.
The short answer would be that you also need to add a dragover listener to the drop area in order to allow the drop action to happen.
function handleDragOver(e) {
if (e.preventDefault) {
e.preventDefault(); // Necessary. Allows us to drop.
}
e.dataTransfer.dropEffect = 'move';
return false;
}
You have a detailed explanation in this step by step tutorial (although the elements in that tutorial act as both draggable elements and drop areas)
However, Chris, as much as I am glad you are experimenting with the native HTML5 drag and drop feature please accept my humble opinion when I say that your code has way too many serious mistakes both at markup level and Javascript level. i.e. missing tags, closing tags that don't exist, wrong attribute namespaces, repeated listeners in chained elements, repeated variables inside the same scope, etc. I'd suggest to go through several code reviews first.

Jquery Click Event Not Firing On First Click, but does on second click, why?

I've got a jQuery code, which
$("a.reply").click(function() {
//code
});
When I click the link with .reply class the first time, nothing happens. The second time I click, the code inside the click function works.
The link is being inserted on the page using PHP from a mysql database. so it's not being inserted dynamically.
Why is this happening? Any solution?
The BadASS Code:
$(function(){
//TextArea Max Width
var textmaxwidth = $('#wrapper').css('width');
//Initialize Focus ids To Different Initially
var oldcommentid = -1;
var newcommentid = -2;
//End Of initialization
$("a.reply").click(function() {
newcommentid = $(this).attr('id');
if (newcommentid == oldcommentid)
{
oldcommentid=newcommentid;
$("#comment_body").focus();
}
else
{
$('#comment_form').fadeOut(0, function(){$(this).remove()});
var commetformcode = $('<form id="comment_form" action="post_comment.php" method="post"><textarea name="comment_body" id="comment_body" class="added_comment_body" rows="2"></textarea> <input type="hidden" name="parent_id" id="parent_id" value="0"/> <div id="submit_button"> <input type="submit" value="Share"/><input type="button" id="cancelbutton" value="Cancel"/></div></form>');
commetformcode.hide().insertAfter($(this)).fadeIn(300);
//
var id = $(this).attr("id");
$("#parent_id").attr("value", id);
oldcommentid=newcommentid;
//dynamicformcreation function
dynarun();
//
}
return false;
});
dynarun();
function dynarun()
{
//Form Re-Run Functions
$('#comment_body').elastic();
texthover();
$("#comment_form input, select, button").uniform();
textareasizer();
$("#comment_body").focus();
$("abbr.timestamp").timeago();
return false;
}
//TextArea Resizer Function
function textareasizer(){$("#comment_body").css('max-width', textmaxwidth);return false;}
//Other Miscellaneous Functions
$('.comment-holder').hover(
function(event) {
$(this).addClass('highlight');
},
function(event) {
$('.comment-holder').removeClass('highlight');
}
);
function texthover()
{
$('.added_comment_body').hover(
function(event) {
$(this).parent().parent().addClass('highlight');
},
function(event) {
$('.comment-holder').removeClass('highlight');
}
);
return false;
}
});
This is a longshot, but are you running some sort of tracking script? Like webtrends or coremetrics (or even some of your own script, that's globally looking for all clicks)? I ran into a similar problem a while ago, where the initial-click was being captured by coremetrics. Just a thought.
Does it still happen if you comment out all your code and simply have an alert("hi") inside the click function?
Update
I think Sarfaz has the right idea, but I would use the document ready function like so
$(document).ready(function(){
$("a.reply").click(function() {
//code
});
});
I just ran into same problem and I resolved my problem by removing:
<script src="bootstrap.js"></script>
you can use bootstrap.min.js
Use Inline CSS for hiding div and use JS/jQuery to show . This way Jquery Click Event will Fire On First Click
<div class="about-block">
<div class="title">About us</div>
<div class="" id="content-text" style="display:none;">
<p>Show me.</p>
</div>
</div>
<script>
var x = document.getElementById("content-text");
jQuery( '.about-block' ).click(function() {
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
});
</script>