drop down is not hidden when I click outside - javascript

This is my script. The script works when i click but it is not hidden when i click outside.
$(document).ready(function() {
//Translate(); //caling Language Translater function
$("#translate_image").attr('href', base_url)
$("#select_lang").click(function() {
$("#lang_visible").attr('style', 'visibility: visible');
})
})
Here's my HTML:
<li>
<div class="clsCurrent_Lan ">
<a class="clsHead_Link_Bg" href="#" id="select_lang">
<span>Select Language</span>
</a>
</div>
<ul id="lang_visible" >
<?php foreach($language_drops as $lang){?>
<li>
<a href="<?php echo admin_url('home/ch_language/' .
$lang->language_code)?>"
id="<?php echo $lang->language_code?>">
<?php echo ucfirst($lang->language_name);?></a>
</li>
<?php }?>
</ul>
</li>

$(document).mouseup(function(e) {
if ($(e.target).parents('#select_lang').length === 0) {
$("#lang_visible").attr('style', 'visibility: hidden');
}
});
Try that. Add it within your document ready call. Basically clicking anywhere besides in the #select_lang selector will cause the visibility of #lang_visible to be hidden.

I think you are going about this the wrong way, sort of like reinventing the wheel. So the behavior you want is to have a control where the user can select a language from a number of different languages? Rather than trying to roll your own, why not just use the "Select" element? You can use php to set up the "Select" initially, and then use javascript/jQuery to respond to state changes.

So, something like this then?
$(document).ready(function () {
//Translate(); //calling Language Translater function
$("#translate_image").attr('href',base_url);
$("#select_lang").click(function () {
$("#lang_visible").attr('style','visibility: visible').click(function (e) {
$(this).hide(); //hides the #lang_visible element
//$(this).parent().hide(); //to hide the <li> containing the #lang_visible element
e.preventDefault();
return false;
});
});
});

Related

Open one drop-down, close another with JavaScript

I am using this script to open a drop down menu and then close it when anything else but the trigger is clicked. Now I am trying to add a second drop down to another area on the page and repeat the script but it is breaking.
For instance, I click button A (Gravatar), and drop down A opens.
However when I add the second script and click button B (category) to open drop down B, down down A stays open.
Also adding the second script breaks the drop down close function of the first script.
Here is the script:
<script>
function openAccount(event) {
event.stopPropagation();
document.getElementById("gravatar").classList.toggle("open");
}
window.onclick = function(event) {
document.getElementById("gravatar").classList.remove("open");
}
</script>
<script>
function openCategory(event) {
event.stopPropagation();
document.getElementById("category").classList.toggle("open");
}
window.onclick = function(event) {
document.getElementById("gravatar").classList.remove("open");
}
</script>
<li class="gravatar">
<a href="#" class="dropbtn" onclick="openAccount(event)">
<img src="<?php echo $gravatar; ?>" alt="" />
<span class="fa fa-icon fa-caret-down"></span>
</a>
<ul class="dropdown" id="gravatar">
<li class="header">
<?php echo $user['email']; ?>
</li>
</ul>
</li>
<div class="category">
Properties<span class="fa fa-icon fa-caret-down"></span>
<div id="category">Test</div>
</div>
Goals:
Multiple drop down menus on different parts of the page.
On click opens drop down.
Click on anywhere else on the page closes the drop down.
On click also closes any previously opened menu.
I'd do something really simple like putting a data* attribute on the element that's clicked on that contains the ID of the element to show or hide, e.g.
// Toggle hidden class on/off
function toggleVis(event) {
// Stop click on element bubbling (to body)
event.stopPropagation();
// Get target element
var el = document.getElementById(this.dataset.id);
// If non-target elements are visible, hide them
hideAll(el);
// Toggle target
el.classList.toggle('hidden');
}
// Hide all, excluding passed element
function hideAll(el) {
Array.from(document.querySelectorAll('ul:not(.hidden)')).forEach(function(node){
if (el != node) node.classList.add('hidden');
});
}
// Attach listeners
window.onload = function() {
// Add to linkLike spans
Array.from(document.querySelectorAll('.linkLike')).forEach(function(node) {
node.addEventListener('click', toggleVis, false);
});
// Add hideAll listener to wndow
window.addEventListener('click', hideAll, false);
// Run hideAll
hideAll();
}
/* style span like link */
.linkLike {
text-decoration: underline;
cursor: pointer;
}
/* class to hide element */
.hidden {
visibility: hidden;
}
<ul id="a"><li>A</ul>
<ul id="b"><li>B</ul>
<ul id="c"><li>C</ul>
<ul id="d"><li>D</ul>
<div><span class="linkLike" data-id="a">Toggle A</span></div>
<div><span class="linkLike" data-id="b">Toggle B</span></div>
<div><span class="linkLike" data-id="c">Toggle C</span></div>
<div><span class="linkLike" data-id="d">Toggle D</span></div>
Of course there are other ways to do the association, but ID is simple, explicit and doesn't depend on document layout or formatting.

Hide/show div with javascript and while loop

I am trying for hours now and for some reason i can't find a solution for my problem.
The thing is, i need something like a div thats showing up when i click on an link.
That's working so far.
But the main problem is, that i need it work within a while loop. So i can get the data dynamically into grid, but all of the php created links have the same id and all of the "to-show-divs" show up at the same time. so my question is how can i create dynamic ids or classes and how do i get them to work within javascript?
echo "<div class='grid grid-pad'>";
$db=mysql_query("SELECT * FROM work") or die (mysql_error());
while($var=mysql_fetch_array($db))
{
echo "<div class='col-1-3'>
<div class='content'>
<div id='thumb' ><img alt='$var[id]' src='$var[thumb]'/></div>
<div class='menu' style='display: none;'>$var[link]</div>
</div>
</div>";
}
echo "</div>";
<script>
$(document).ready(function() {
$('#thumb').click(function() {
$('.menu').slideToggle("fast");
});
});
</script>
You can do what the comment suggests or just make an iterator variable and concat that to the id like so:
$index = 0;
while($var=mysql_fetch_array($db))
{
echo "<div class='col-1-3' id='item_". $index ."'>
<div class='content'>
<div id='thumb_". $index++ ."' >STUFF</div>
<div class='menu' style='display: none;'>$var[link]</div>
</div>
</div>";
}
Change <div id="thumb"> to <div class="thumb"> and then use following jQuery:
$('.thumb').click(function() {
$(this).next('.menu').slideToggle("fast");
});
Otherwise you'll have multiple elements with the ID "thumb", which you shouldn't.
Since the DIV is right after the link, you can use the JQuery function next() to get the next node after the link, which is the DIV:
$(document).ready(function() {
$('#thumb').on('click', function(e) {
// prevent IE from actually executing the href of the link
e.preventDefault();
// get next node, call the toggle.
$(this).next().slideToggle("fast");
// prevent executing of the href of the link
return false;
});
});
If you have more of these "thumb" links, please us a class instead of an ID - an ID has to be unique.
Edit:
Realizing that there actually are no links but DIVs, you can skip the "prevent executing" stuff of course.

jquery AJAX call only works once?

I'm setting up some sort of small form to determine whenether my users want to submit a form anonymously or not, and whenether the content they're submitting is original or not.
The first AJAX call seems to work fine, but then when the new content is loaded from a PHP file through AJAX, then the jQuery function doesn't seem to work.
It is supposed to work like this.
They are presented with 2 options, submit with username, or submit anonymously (clicking either of these calls an AJAX request to the specified PHP file)
The PHP file contains another 2 options (see example below) called Original and Existing. (Clicking any of these doesn't seem to do anything!)
Finally, they should be presented with the specific submission form for their choices.
Here is my code:
jQuery
// User
$('#user-submission').on( "click", function() {
$.ajax({url:'<?php echo get_template_directory_uri(); ?>/submission/user-submission.php',success:function(result) {
$("#submit-section").html(result).fadeIn('slow');
}});
});
// Anonymous
$('#anonymous-submission').on( "click", function() {
$.ajax({url:'<?php echo get_template_directory_uri(); ?>/submission/anonymous-submission.php',success:function(result) {
$("#submit-section").html(result).fadeIn('slow');
}});
});
// User -> Original
$('#original-submission-user').on( "click", function() {
$.ajax({url:'<?php echo get_template_directory_uri(); ?>/submission/original-user-submission.php',success:function(result) {
$("#submit-section").html(result).fadeIn('slow');
}});
});
// User -> Existing
$('#original-submission-anonymous').on( "click", function() {
$.ajax({url:'<?php echo get_template_directory_uri(); ?>/submission/original-anonymous-submission.php',success:function(result) {
$("#submit-section").html(result).fadeIn('slow');
}});
});
// Anonymous -> Original
$('#existing-submission-user').on( "click", function() {
$.ajax({url:'<?php echo get_template_directory_uri(); ?>/submission/existing-user-submission.php',success:function(result) {
$("#submit-section").html(result).fadeIn('slow');
}});
});
// Anonymous -> Existing
$('#existing-submission-anonymous').on( "click", function() {
$.ajax({url:'<?php echo get_template_directory_uri(); ?>/submission/existing-anonymous-submission.php',success:function(result) {
$("#submit-section").html(result).fadeIn('slow');
}});
});
Main HTML
<section id="submit-section">
<div class="anonymous-or-credited">
<a href="#" id="user-submission" class="submit-url">
<div class="transition">
<h2><?php echo $current_user->display_name; ?></h2>
<h3>Submit a as <?php echo $current_user->display_name; ?></h3>
</div>
</a>
<a href="#" id="anonymous-submission" class="submit-url">
<div class="transition">
<h2>Anonymous</h2>
<h3>Submit a Creepypasta Anonymously</h3>
</div>
</a>
</div>
</section>
PHP file containments
<div class="anonymous-or-credited">
<a href="#" id="original-submission-user" class="submit-url">
<div class="transition">
<h2>Original</h2>
<h3>I wrote this myself</h3>
</div>
</a>
<a href="#" id="exisiting-submission-user" class="submit-url">
<div class="transition">
<h2>Existing</h2>
<h3>I found this elsewhere</h3>
</div>
</a>
</div>
If the elements are added dynamically, selecting for the ID of the dynamically-added element will not work. You will have to instead listen for event to bubble up in a location higher up (in terms of hierarchy) on the DOM tree, like document.
I assume that both #user-submission and #anonymous-submission are already present on the page when it is initially loaded, but the rest are not. Therefore, you need to listen to the click event bubbling up to document (or any parent that is already present on the page when JS is executed):
$(document).on('click', '#original-submission-user', function() {
$.ajax({url:'<?php echo get_template_directory_uri(); ?>/submission/original-user-submission.php',success:function(result) {
$("#submit-section").html(result).fadeIn('slow');
}});
});
Remember to repeat this for all dynamically-added elements which you want to bind events to.
If I'm understanding correctly, you have JS bindings to HTML that exists on page load -- but when you dynamically load more HTML, your existing JS isn't bound to it. One solution would be to add your click bindings to the ajax callback, after the HTML is loaded.
You need to enter the second parameter of the .on() function (delegated event):
$('#submit-section').on('click','#original-submission-user', function() {
});

smarty dropdown with javascript

I'm trying to make a friends list where you can click the button at the top for a drop down menu.
<script>
var dropAll = false;
function changeAllFriendsDrop()
{
if (dropAll == false)
{
dropAll = true;
}
else
{
dropAll = false;
}
}
</script>
My function is simple enough but when i try call it onClick it doesn't seem to be working.
<li role="heading" data-role="list-divider" style="color:#F25A97">
<a >
<button onclick="changeAllFriendsDrop()">All Friends </button>
</a>
</li>
{$friend = array("Josh","Phil","Paul","Sean")}
{if !empty($friend)}
{foreach $friend as $person}
<script> if (dropAll == true){ </script>
<li data-theme="a" style="color:#F25A97">
<a href="">
{$person}
</a>
<a align="left" style="size: 10px">
Last Seen: {$lastLocation}
</a>
</li>
<script> } </script>
{/foreach}
{/if}
It doesn't seem to call the function so the if statement cannot be checked, any advice would be greatly appreciated.
Your callback function dropAll isn't actually causing anything to change on the page, it is just setting a variable. The line if (dropAll == true) will only be evaluated once, and even then will not do anything useful - a JavaScript if like that won't tell the browser to hide content, that's just not how it works. (In fact, since each <script> tag is evaluated separately, you are probably getting a JavaScript error because there's no } in the first <script> tag.)
What you need to do is write a JavaScript function which actually toggles the visibility of those parts of the page. I would strongly recommend using a JavaScript library such as jQuery rather than doing this in "plain" JavaScript.
For instance, if you gave each of the elements you want to toggle class="togglableFriendItem", you could use the jQuery .toggle() function like this:
function toggleAllFriendsDrop()
{
$('.togglableFriendItem').toggle();
}

JQuery's .on() not working correctly

I'm setting things up very simply and i just can't wrap my brain why this won't work. I know this is correct, yet it doesn't work.
.navigate-button is being ajax'd into .overlay-content so .overlay-content isn't in the dom on page load, hence using .on
When i click the link it just takes me to the page as normal. I know that the even tisn't being bound to .navigate-button
Mark Up:
<div class="overlay" id="overlay">
<div class="overlay-content--bg">
<div class="overlay-content">
<a class="navigate-button left" href="/question.php?id=<?php echo $json->id-1;$json->id+1; ?>">
<
</a>
<a class="navigate-button right" href="/question.php?id=<?php echo $json->id+1; ?>">
>
</a>
</div>
</div>
</div>
JS: if i run this code in console it works as expected
$('#overlay').on('click','.navigate-button', function(){
var id = $(this).attr('href');
id = id.split('=');
console.info(id[1]);
callPage(id[1]);
return false;
});
function callPage (id) {
$.ajax({
url:'/question.php?id='+id,
success: function(data){
$('.overlay-content').html(data);
FB.XFBML.parse(document.getElementById('overlay'));
$('.overlay').fadeIn();
}
});
}
We solved this in chat. Jamie's problem was that the click event on the .navigate-button div wasn't bubbling up to the #overlay div because it was being caught and handled in between by a handler that called .stopPropagation on it. The solution was to remove that intermediate handler.
Have you tried this?
$(document).on('click', '.navigate-button', function() {
YOUR FUNCTION
});

Categories

Resources