How to enable and disable document event handler (specifically click) - javascript

I have a button, clicking on which, I have to enable the click event handler on the entire document. Once someone clicks now, I want to capture the dom selector of that element and disable the event handler again.
Is this question asked already? I searched a lot but couldn't find anything relevant. There are a lot of solutions on enabling or disabling event handler on a particular element, but I have to do it over the entire document. Here is my code -
JavaScript -
<script>
var select_target = false;
$(document).click(function(event) {
if (select_target) {
element.style.backgroundColor = "#FDFF47";
var text = $(event.target).text();
console.log(text) //This text should be the DOM Selector, which I'm not able to retrieve
select_target = false
}
})
$('.select_target').click(function() {
select_target = true
})
</script>
HTML -
<!-- Lot of code from the other parts of the webpage -->
<button name="ignore" type="button" class="btn btn-primary btn-md m-1 select_target">
Select Target
</button>
<!-- Lot of code from the other parts of the webpage -->
This gives me Select Target as the output instead of the DOM Selector of the element, which I wasn't expecting to be the target button in the first place, but whatever I click after clicking the select target button.
I know the code looks clumsy, but any help would be appreciated. Thanks!

It looks like the following code does what I'm expecting. It's for everyone who wants a similar thing to happen i.e., To be able to select the element from the page on which you want to perform specific operations with a clean and modifiable code.
Javascript -
<script>
var select_target = false;
$(document).click(function(event) {
if (select_target) {
event.preventDefault(); //If you click a link or a button, this helps in just selecting it and it won't perform it's default operation.
var text = $(event.target).text();
console.log(text)
select_target = false;
}
})
$(document).ready(function() {
$("body *").mouseenter(function(el){
if(select_target){
$(el.target).addClass("red-hover-box"); //To highlight the elements on hover
}
})
$("body *").mouseout(function(el){
if(select_target){
$(el.target).removeClass("red-hover-box"); //To remove the highlight on the elements. This will keep the element highlighted if you click on it, since the select_target's value would be false after the click.
}
})
})
$('.select_target').click(function() {
e.stopPropagation(); //To prevent the click on the button to be handled by the event listener.
select_target = true
})
</script>
CSS -
.red-hover-box{
border:1px solid red;
}
HTML -
<!-- Lot of code from the other parts of the webpage -->
<button name="ignore" type="button" class="btn btn-primary btn-md m-1 select_target">
Select Target
</button>
<!-- Lot of code from the other parts of the webpage -->
I'm still now able to figure out on how to get a unique identifier for the HTML element that has been clicked, and would update this answer once it's been figured out.
Thanks!

Related

Saving into Local Storage with a Click Event

Hello stackoverflow: I am working on getting a click event save into local storage. However, I get that it is undefined as the answer. This is what I have so far as my click event:
$(document).ready(function() {
$(".btnlocalStorage").on("click", function() {
event.preventDefault();
console.log("I am clicked!")
var myContent = $(this).(".btnlocalStorage").val();
localStorage.setItem("myContent", myContent);
//localStorage.setItem("myContent", JSON.stringify(myContent));
})
})
This is the HTML part of it, a button and a text area:
<textarea type="text" class="TextBoxColors-17 form-control" id="TextBoxStorage-17" aria-label="5:00 PM" aria-describedby="inputGroup-sizing-sm"></textarea>
<button class="btn btn-primary btnlocalStorage" type="button" todo="saveToDo-11am"><i class="fa fa-floppy-o" style="font-size:18px;"></i>
</button>
What should happen is that when I type any content into the text area, when I click the save button, this content should be saved into local storage. I am getting the key name, but the value/content undefined. Please, help me get this working. Thanks!
You're trying to get the value of your button instead of the value of the textarea with:
$(this)
Your code should look like this :
$(document).ready(function(){
$(".btnlocalStorage").on("click", function() {
localStorage.setItem("myContent", $(".TextBoxColors-17").val());
console.log(localStorage.getItem("myContent"));
})
});
EDIT :
This code only works for one specific textarea, if you want to make it work for multiple textareas followed by a button, you must use :
$(this).prev()
"this" refers to the button wich triggered the event and the prev() function allow you to get the element just before it.
Be careful, your local storage item must have a different name from one button to another, otherwise all buttons will override the same item content, for the example I took the ID of your textarea but it can be any iterated variable :
$(document).ready(function(){
$(".btnlocalStorage").on("click", function() {
localStorage.setItem($(this).prop("id"), $(this).prev().val());
console.log(localStorage.getItem($(this).prop("id")));
})
});

jquery mobile popup - better way to retrieve data?

I'm using this simple popup correctly initialized along with corresponding popupafterclose handler, wrapped appropriate in content div. It just works. -
<div id="start-activity-popup" data-role="popup">
here is popup.
<button id="start">Start</button>
<button id="cancel">Cancel</button>
</div>
But if I had to retrieve values from popup or know which button
was pressed - do I need to write another handler for each - start and cancel buttons ?
Is there a better way ?
You can just write one handler:
$("#start-activity-popup button").click(function() {
var clicked = this.id; //this is the id of the clicked button
//do stuff
});

Change element by click like PHPAdmin

I am beginner of js. I want to make a editor like PHPAdmin. When click its table, the field will change to text-area. When click some where else outside of the text-area, it will change back to the filed and execute the sql.
Following is what I suppose to write with jQuery, I am totally not understand how should I code it further, please advice.
$('#editor #gird_edit').bind({
click: function() { //When Click
var content = $(this).text(); // read what is in the filed
$("#gird_edit").text('<textarea>'+a+'</textarea>'); // This is not work, will only add html code,not change to text-area
},
/* ??? */: function() { //Outside click of the text-area
var content = $(this).text(); // read what is in the text-area
$("#gird_edit").text(????); // change back to the filed
}
})
Html
<div id='editor'>
<div id='gird_edit'>hallo world</div>
<div id='gird_edit'>hallo world 2</div>
<div id='gird_edit'>hallo world 3</div>
</div>
I only have 3 reputations, just joined yesterday...I am sorry for that I cannot vote you since it requires 15 reputations. However, I will very appreciate you help!!
If you want to detect clicks outside of an element, just detect them on the whole page, and throw out any that come from inside the element. In other words:
$('body').on('click', : function(e) { //Outside click of the text-area
if ($(this).parents().is('#gird_edit')) return false;
var content = $('textarea').text(); // read what is in the text-area
$("#gird_edit").text(????); // change back to the filed
});
However, it sounds like what you're really looking for is a "blur" handler, which will trigger whenever someone was inside a textarea and just left it; you can make one of those the same basic way you made your click handler:
$('#gird_edit textarea').bind({
blur: function() {
// do the reverse of the click handler
}

jQuery Tools Overlay - Two buttons with different close conditions

I have the following jQuery Tools overlay:
<div id='editDescriptiontOverlay' class='overlay'>
<input type='text' class='description'/>
<button class='save'>Save</button>
<button class='close'>Cancel</button>
</div>
Background info: The HTML for this overlay is static. I have a list of items each having their own Edit link. When a given Edit link is clicked, the overlay is generated by calling: $('a[rel=#editDescriptionOverlay]').overlay( { ... } ); and the input is populated with the respective text.
The Save button needs to validate the text in the input element and close the overlay if and only if the validation is successful. Otherwise, the overlay must remain open. The Cancel button simply closes the overlay without validation.
The validation logic has been independently verified to work.
I've tried setting the onBeforeClose event during overlay generation as a means of validation. Taking this approach, both the Save and Cancel buttons needed the same class .close. Unfortunately, the condition applies to all .close elements in the overlay so even the Cancel button was validating.
I've also tried binding a click event to the Save button immediately after generating the overlay, like so:
$('.save', $('#editDescriptionOverlay'))
.unbind('click')
.bind('click', function() {
if (validateText) {
console.log("Validation passed.");
$('a[rel=#editDescriptionOverlay]').overlay().close();
}
else {
console.log("Validation failed.");
}
});
The console.log's confirm that the validation is working, but the overlay doesn't close.
Any insight is appreciated, thanks.
For jquery widgets, public methods should be called as follows:
$('a[rel=#editDescriptionOverlay]').overlay("close");
wherein close is the method name that you wish to call.
If a method accepts parameters, then, these should be added as parameters right after the method name.
Updated:
I am sorry. I just had time to check what jQuery Overlay Tools is and I am mistaken. This is not similar to any jQuery widget, hence, my comment above will also not work for this case. I tried your code above and it worked. The overlay was closed. But, when I tried it with multiple <a rel="#editDescriptionOverlay">, which I think is what you did. It did not work. My suggestion would be to use just one <a rel="#editDescriptionOverlay"> and use a dummy anchor element for the Edit link, which when clicked would trigger a click to <a rel="#editDescriptionOverlay">. You can do something like this:
<script type="text/javascript">
$(document).bind("ready", function(e){
$("a[rel]").overlay();
$('.save', $('#editDescriptionOverlay')).unbind("click").bind("click", function(){
if (validationValue){
$("a[rel=#editDescriptionOverlay]").overlay().close();
}
});
});
function clickThis(){
$("a[rel=#editDescriptionOverlay]").trigger('click');
return false;
}
</script>
Edit1
Edit2
<a rel="#editDescriptionOverlay">Dummy</a>
<div id='editDescriptionOverlay' class='overlay'>
<input type='text' class='description'/>
<button class='save'>Save</button>
<button class='close'>Cancel</button>
</div>
I'd prefer binding an event to the save button (the second one you mentioned). Actually your code looks fine, except that you probably don't need to bind the event to $('#editDescriptionOverlay') and you have typo in your html markup above (<div id='editDescriptiontOverlay' should be <div id='editDescriptionOverlay').
See here for an example.

How do a get buttons not to take the focus?

I want my (ExtJS) toolbar buttons not to grab the focus on the web page when they are clicked, but to do their "thing" while leaving the focus unchanged by the click. How do I do that?
Cancelling the default behavior of onmousedown prevents an element from getting the focus:
// Prevent capturing focus by the button.
$('button').on('mousedown',
/** #param {!jQuery.Event} event */
function(event) {
event.preventDefault();
}
);
document.activeElement stores the currently focussed element.
So on your toolbar, you can add a "mousedown" handler to this function :
function preventFocus() {
var ae = document.activeElement;
setTimeout(function() { ae.focus() }, 1);
}
Try this example :
<html>
<head>
<script>
function preventFocus() {
var ae = document.activeElement;
setTimeout(function() { ae.focus() }, 1);
}
</script>
</head>
<body>
<input type="text"/>
<input type="button" onmousedown="preventFocus()" onclick="alert('clicked')" value="Toolbar" />
</body>
</html>
This usually does the trick for me:
<button
tabindex="-1"
onclick="javascript:console.log('do your thing')"
>My Button</button>
From https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex:
A negative value (usually tabindex="-1") means that the element should be focusable, but should not be reachable via sequential keyboard navigation. It's mostly useful to create accessible widgets with JavaScript.
I don't think there's an easy way to do what you want to do because it's the browser's default behaviour.
You could of course blur() the button as soon as it is clicked, but that would simply unselect everything. To have the previously active object regain focus, you'd have to create a "memory" of sorts by adding a blur handler for every element to keep track of which element had/lost focus last (store the id of the element in a global and update it when an element loses focus).
The top-voted answer is technically correct, but depends on jQuery...
Here's a simpler example:
<span onclick="document.execCommand('bold', false);" onmousedown="event.preventDefault();"></span>
My solution is to replace <button /> with <div /> and style it as a button.
Looks like Div doesn't take a focus on it when you click it.
Because the toolbar buttons are just styled ordinary HTML button elements then this is an actual browser behavior, and you should think twice before changing it. But nevertheless...
You should be able to prevent the botton from receiving focus by just returning false from its onclick handler.
Maybe you should try to use stateful and state change properties for form fields or whatever to get focus back?
I would attach one blur event listener to all fields. This listener should save the field, that lost the focus, in a global variable.
Then all the toolbar button should get one focus event listener. This listener should focus the field, that was saved as described above.
This code should work, although it didn't test it
<script>
function focusor(){
document.getElementById('focus').focus;
}
document.onkeydown = focusor;
document.onclick = focusor;
</script>
<div style="width: 0px; height: 0px; overflow: hiddden;">
<button id="focus"></button>
</div>
What I have found, is you will have to make a dummy element, I found buttons to work best in this situation. put the button in a div and make the div 0px.
[do not make the div display none, some browsers will just ignore it]
Basically any click or button presses, it will focus on this dummy button.
I had a project very similar and whenever they pressed the down key it selected the first button on the page, this just focuses on the button over and over again.
Sort of jacked up, but it works.
All these answers are wack. Here's a very excellent trick that only uses CSS
<button type="submit" disabled>
<span>Submit</span> <!-- the <span> is the secret -->
</button>
Now in your css:
button[disabled] > * {
pointer-events: none;
}
The trick is the inner span has to be used, otherwise the button will still steal focus away from inputs.

Categories

Resources