Jquery hide and show a button - javascript

First off, I've read extensively by now into what seem to be recurrent questions about how to hide a div after a properly detecting a click, or event, outside the div; indeed this has influenced my javascript code. But I'm a newbie and it's not working so I hope you can help me out.
Second, the jfiddle - https://jsfiddle.net/u5uzexqk/ ... please note the button should show when the any section of the search bar or indeed button is clicked on; and not show when a click anywhere outside is detected.
Before the code, I would just like to point out I have also read into the e-propagation thing, however I don't think it's the absence of that which is the problem; if it is, my profuse apologies.
Perhaps owing to the fact I'm new to Javascript, I can't see how the suggested answer from another question helps; the Jfiddle on the most popular answer seems to do the opposite - remove the menu when the menu link is clicked again.
Html
<body>
<div id = "wrapper">
<form action="" class="search-form">
<div class="cell">
<input type="text" name="q">
</div>
<div class="cell button-holder">
<button type="submit" id="dropdownbutton">
<span>Search</span>
</button>
</div>
</form>
</div>
</body>
Javascript
$("#wrapper").onclick(function (e){
document.getElementById('#dropdownbutton').style.visibility = 'visible';
}
$(document).mouseup(function (e)
{
var container = $("#wrapper");
if (!container.is(e.target) // if the target of the click isn't the container...
&& container.has(e.target).length === 0) // ... nor a descendant of the container
{
$("#dropdownbutton").hide();
}
});
});

You are mixing methods for hiding and showing. If you are going to use .hide() then use .show() when showing it.
With your code, the call to .hide() will set the style to display: none, but then your native Javascript technique to show the button (which also contains the pound symbol in the id i.e. document.getElementById('#dropdownbutton') - don't confuse it with jQuery's selector when calling document.getElementById()) just adds a style for visibility: visible. Those are different properties.
<button type="submit" id="dropdownbutton" style="display: none; visibility: visible;">
<span>Search</span>
</button>
Also, as was pointed out in comments, there is no jQuery method .onclick. Use .click(). Also, there is a missing closing parenthesis after the click handler for the wrapper button. So update it like this:
$("#wrapper").click(function(e) {
$("#dropdownbutton").show();
}); // <- add parenthesis (and optional semi-colon) to terminate the function call
And has already been mentioned, you should wait until the DOM is ready to access elements. With jQuery, use document.ready().
$(document).ready(function(readyEvent) {
//interact with DOM
//now that the DOM is ready
//e.g. fetch elements by id attribute, add event handlers, etc.
});
See these changes in action in the snippet below:
$(document).ready(function() {
$("#wrapper").click(function(e) {
//document.getElementById('dropdownbutton').style.visibility = 'visible';
$("#dropdownbutton").show();
});
$(document).mouseup(function(e) {
var container = $("#wrapper");
if (!container.is(e.target) // if the target of the click isn't the container...
&& container.has(e.target).length === 0) // ... nor a descendant of the container
{
$("#dropdownbutton").hide();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">
<form action="" class="search-form">
<div class="cell">
<input type="text" name="q">
</div>
<div class="cell button-holder">
<button type="submit" id="dropdownbutton">
<span>Search</span>
</button>
</div>
</form>
</div>

First let's point out some issues in your code:
There is no such function as onclick in jQuery. To attach a click event you either use: $(...).click(callback) or $(...).on("click", callback).
The oposite of show is not visibility = "visible". show uses the display property (show = display = "none") and its oposite is hide (display = ""). So use show and hide.
Since you are already using jQuery, why use document.getElementById, just $("#id") will do.
Instead of all those checks to see if the target is the wrapper or something inside the wrapper, just stop the propagation of the event inside the event listener of the wrapper so it will never reach the document.
You should wrap your code inside a load event- $() will do- To make sure that everything is loaded before starting doing anything.
$(function() {
$("#wrapper").click(function(e) {
$("#dropdownbutton").show();
e.stopPropagation(); // if the event occur inside the wrraper, prevent it from bubbling up to the document and fires the bellow function
});
$(document).click(function(e) { // if the click target is the #wrapper (or something inside it) this event will never reach the document because of the stop propagation inside the above listener. So if this is fired then the target is not the wrapper, therefore we should hide the button
$("#dropdownbutton").hide();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="wrapper">
<form action="" class="search-form">
<div class="cell">
<input type="text" name="q">
</div>
<div class="cell button-holder">
<button type="submit" id="dropdownbutton">
<span>Search</span>
</button>
</div>
</form>
</div>
</body>

I would do it like this:
$("document").ready(function(){
$("#dropdownbutton").hide();
$( "input[name=q]" ).on( "focus blur", function() {
if($(this).is( ":focus" ) ){
$("#dropdownbutton").show();
}else{
$("#dropdownbutton").hide();
}
});
});
Demo: http://codesheet.org/cs/wAnG3ofQ

Related

How do I hide an specific division when someone clicks an button with HTML, JS or Ajax?

So i want to hide (better to say toggle) some division when someone clicks an button. I have more than 20 division and 20 button, each button should close the specified division. For easier understanding lets do it just with one division and one button.
so i have 2 parts, here is what i tried:
html part which I have
<div class="sssadsa" id="buttonsdiv">
<button id="thebutton" type="button" onclick="toggleDiv(divtohide0);">
<h3>Scene 1</h3>
</button>
</div>
<div id="divtohide0">
some content
</div>
and this is my WHOLe javascript which I have
but somehow I cannot manage it to get working, the js doesn't do anything when clicking the button. not even the alert("hello world");
function toggleDiv(id){
alert("hello world -back to the roots" );
event.preventDefault();
$('#' + id).toggle(); // Toggle div visibility
}
There can be several things that might occur.
Your javascript isn't loaded (try running a console.log outside the function and check if you see anything. If you don't check the way you are loading the script)
toggleDiv isn't available globally (try adding window.toggleDiv = toggleDiv after you declared the function)
If any of the above doesn't work, leave a comment.
Also note the following errors in your code:
You cannot call the event if you pass another parameter (eg: divtohide0).
You need to use a string to pass the id, otherwise javascript will expect a variable. (eg: toggleDiv('divtohide0');)
I suggest you to avoid adding a h3 tag inside a button. If you need to style the content do it with a class.
In the snipper there is another function where the event works which require a data argument on the button. But there are several ways to achieve the same result.
function toggleDiv(id){
alert("hello world -back to the roots" );
// event.preventDefault(); this won't work
$('#' + id).toggle(); // Toggle div visibility
}
function toggleDivWithEvent(event) {
event.preventDefault();
var id = $(event.target).data('target-id');
$('#' + id).toggle(); // Toggle div visibility
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="sssadsa" id="buttonsdiv">
<button id="thebutton" type="button" onclick="toggleDiv('divtohide0');">
<h3>Scene 1</h3>
</button>
</div>
<div id="divtohide0">
some content
</div>
<div class="sssadsa" id="buttonsdiv">
<button id="thebutton" type="button" data-target-id="divtohide1" onclick="toggleDivWithEvent(event)">
<h3>Scene 1</h3>
</button>
</div>
<div id="divtohide1">
some content
</div>

jQuery closest() remove() on <a> doesn't work?

Please see this page which has this code:
<div class="pure-control-group query-brand-by-column">
<!-- somethings else -->
<div class="pure-u-1 pure-u-sm-1-24 control-group-sub">
X
</div>
</div>
Clicking the X link should remove its ancestor div.query-brand-by-column as a whole but somehow it's not working. I've checked jQuery docs and this answer and the code seems absolutely all right to me but it simply doesn't work. Any idea?
this in href doesn't refers to anchor element, thus it doesn't work. It refers to window.
You should bind element event handler using jQuery.
Script
$(document).on('click', '.pure-button danger' function(e) {
e.preventDefault();
$(this).closest('.query-brand-by-column').remove();
});
HTML
<div class="pure-control-group query-brand-by-column">
<!-- somethings else -->
<div class="pure-u-1 pure-u-sm-1-24 control-group-sub">
X
</div>
</div>
I will not recommended, However you can use inline onclick handler.
<a onclick="$(this).closest('.query-brand-by-column').remove();" href='#' class="pure-button danger">X</a>
Here is your answer, Enjoy
X
Detach your javascript from your html and remove your item with a click event, right now you aren't triggering any click events:
<script>
$(function(){
$('.pure-form').on('click','.query-brand-by-column a',function(){//this will create and delegate your click event to work on dynamically created items
$(this).closest('.query-brand-by-column').remove();
});
});
</script>

Add a click event to an element rendered dynamically from Mustache?

I am trying to add a click event to an element that is added dynamically to the page after document load, but it isn't working, though this seems to be a well-known problem with a clear answer. This is my code:
$('body').on('click', "#clickme", function() {
alert('clicked!', $('#cartodb_id').text());
});
The complicating factor may be that the element is inside a Mustache template that itself gets rendered dynamically into the page, by CartoDB.js:
<div id="map"></div>
<script type="infowindow/html" id="infowindow_template">
<div class="cartodb-popup">
x
<div class="cartodb-popup-content-wrapper">
<div class="cartodb-popup-content">
<h4>cartodb_id: </h4>
<p id="cartodb_id">{{content.data.cartodb_id}}</p>
<input type="submit" id="clickme" value="clickme" />
</div>
</div>
<div class="cartodb-popup-tip-container"></div>
</div>
</script>
Should this affect my ability to add an event dynamically?
Link to a JSFiddle showing the problem in full: http://jsfiddle.net/8o12v2xs/9/
Not too familiar with Carto myself, but it seems to work fine once you wait for the element to exist. http://jsfiddle.net/8o12v2xs/10/
// register events once it's available
sublayer.on('featureClick', function(e, latlng, pos, data) {
$('#clickme').on('click', function() {
alert('clicked!', $('#cartodb_id').text());
})
});
Put that underneath the initialization like in the above Fiddle.

jquery select single tag class onclick

seems a little trivial but am having a hard time solving it, i have a jquery function to select the class of a tag on click but the problem is that it selects every other tag underneath the tag clicked as well in structural order where as i only want the very first one
for example if i have
<div class="1">
<div class="2">
<div class="3">
<p class="4">Hello World</p>
</div>
</div>
</div>
and i clicked on the (p) tag that says hello world i would get an alert
saying 4 then 3 then 2 then 1
but like i said i only want the first one witch in this case is 4
here is my jquery code
$("*").dblclick(function(){
if(!$(this).hasClass("") && !$(this).hasClass("main")){
alert($(this).attr('class'));
}
});
i know the problem is happening because technically i am clicking all of the tags so it continus to loop trough but i still need a way to break it after the first class is selected or better yet is there a way to select only the topmost object
Just add return to the function like so:
$("*").dblclick(function(){
if(!$(this).hasClass("") && !$(this).hasClass("main")){
alert($(this).attr('class'));
return false;
}
});
I would pass in event to your click function, and after you've finished your logic, use event.stopPropagation(). This prevents the event from bubbling up to parent elements
$("*").dblclick(function(event){
if(!$(this).hasClass("") && !$(this).hasClass("main")){
alert($(this).attr('class'));
}
event.stopPropagation();
});
Run this example and look your console.
$("body > div").dblclick(function(){
console.log($(this).attr('class'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="1">
<div class="2">
<div class="3">
<p class="4">Hello World</p>
</div>
</div>
</div>
You should read about event bubbling and event propagation.
Here is function which does what you want:
$("*").dblclick(function(e){
if(!$(this).hasClass("") && !$(this).hasClass("main")){
alert($(this).attr('class'));
e.stopPropagation();
}
});
And here is working example:
https://jsfiddle.net/18sawk57/
Although it's not a good solution to attach event listening to all of the tags on the page. Much better solution is to add for example id or clickable class attribute for elements that should have event listening.
Here is another working example with better approach: https://jsfiddle.net/tr7aqask/
Here is another working example with bubbling disabled using jquery: https://jsfiddle.net/yc0481sm/

javascript disabled button ondblclick with this

I have a button that has a doubleclick event, that I want to run, regardless of whether the button is enabled or disabled. I posted a similar question about this here, but now I need to run a function from the disabled button that uses thethis paramater, and if I use the <span> workaround, as described in the other question, it gives me the info about the <span> element, not the <button> element.
jsfiddle example
How can I get round this?
First of all, you can't have two elements with same ids. Your markup should look like that:
<button name='name_of_button' id='id_of_button1' ondblclick="runFunction( this );">Enabled Button</button>
<br>
<button name='name_of_button' id='id_of_button2' ondblclick="runFunction( this );" disabled>Disabled Button</button>
Second, it is not a good idea to use inline javascript. However, your problem could be solved like that:
HTML:
<div class="wrapper">
<button name='name_of_button'>Enabled Button</button>
<div class="over"></div>
</div>
<div class="wrapper">
<button name='name_of_button' disabled="disabled">Disabled Button</button>
<div class="over"></div>
</div>
JS:
window.onload = function() {
var dblClicked = function() {
console.log(this.parentNode.childNodes[1].removeAttribute("disabled"));
}
var overlays = document.querySelectorAll(".wrapper .over");
for(var i=0; i<overlays.length; i++) {
var over = overlays[i];
over.addEventListener("dblclick", dblClicked);
}
}
http://jsfiddle.net/NRKLG/12/
If the element is disabled it can't trigger events. This means that you can't listen for dblclick even if you add the listener to the parent element. So, you should put an overlay transparent div over the button.

Categories

Resources