JQuery's .on() not working correctly - javascript

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
});

Related

jQuery - document.on hover toggle method - error

So, I've been trying to create a function in jQuery where when you hover over an element, it toggles an img, and when you exit the element, the img gets toggled again. The only issue is that this all happens after a $(document).on slector. I've tried using $(document).off().on but it's not working. Here's my code:
$(document).on('mouseover', '.addressLink', function() {
var redirectSelector = $(this).children().last();
redirectSelector.toggle('fast');
$(this).mouseleave(
function() {
redirectSelector.toggle('fast');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='hoverDiv'>
<a class='addressLink' data-toggle='modal' data-target='#myModal'>
Click For Location <img src='download.png' class='redirect display'>
</a>
</div>
This function works the first time, but then the img toggles and toggles again and again, doing it one more time for every mouseover! The event fires once, then twice, then three times, and so on. Thank you for your answers.
I made example for you.
$(document).on('mouseover mouseleave', '.addressLink', function(e) {
var $img = $(this).find('img');
if(e.type === 'mouseover') {
$img.stop(true, true).slideDown('fast');
}else {
$img.stop(true, true).slideUp('fast');
}
});
.addressLink img {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='hoverDiv'>
<a class='addressLink' data-toggle='modal' data-target='#myModal'>Click For Location<img src='https://via.placeholder.com/150X30' class='redirect display'></a></p>
</div>
$(document).on('mouseenter mouseleave', '.addressLink', function() {
var redirectSelector = $(this).children().last();
redirectSelector.toggle('fast');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='hoverDiv'>
<a class='addressLink' data-toggle='modal' data-target='#myModal'>
Click For Location <img src='download.png' class='redirect display'>
</a>
</div>
I would suggest using a single delegate for the mouseenter and leave, since all you are doing is toggling a class. This avoids the duplicate binding issue. There is still a little flakyness with the toggle due to the element moving and the mouse may accidentally leave the target while it is redrawing, but that's an issue with styling or such that can be addresses as a secondary issue.
Try this :
$('.addressLink').hover(function(){
var redirectSelector = $(this).children().last();
redirectSelector.show('fast');
}, function(){
var redirectSelector = $(this).children().last();
redirectSelector.hide('fast');
}
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='hoverDiv'>
<a class='addressLink' data-toggle='modal' data-target='#myModal'>
Click For Location <img src='download.png' class='redirect display'>
</a>
</div>

Trying to click an image and open a modal ajax

Thanks in advance, I just started coding a few weeks ago and I can't figure this out.
I have been trying to set up where you click an image and it opens a modal that is matched by the img tag, and that modal click event will in turn call a method. Problem is that I can't seem to get the onclick event to open the modal, i think once i get that to work I can get the method calls to work. I have tried a bunch of things and can't seem to figure out how to get it to pop up,
here is the JS/ajax
$('#img').click(function(){
$('#vendingModal').dialog('open');
return false;
});
$('#vendingModal').click(function (event) {
event.preventDefault();
var element = $(event.relatedTarget);
var inventoryId = element.data('inventory-id');
var modal = $(this);
$.ajax({
type: "GET",
url: 'inventory/' + inventoryId
}).success(function (inventory) {
modal.find('#inventory-id').text(inventory.inventoryId);
modal.find('#inventory-name').text(inventory.inventoryName);
modal.find('#inventory-price').text(inventory.price);
modal.find('#inventory-count').text(inventory.count);
});
});
here is the jsp
<%# page pageEncoding="UTF-8" %>
<div class="column2" id="inventoryGrid">
<div class="row">
<div class="col-xs-3 offset-3-12">
<div class="pic morph">
<img id="item1" src="img/item1.jpg" alt="3 Musketeers" title="3 Musketeers" class="img-rounded img-responsive" style="width:128px;height:128px">
</div>
</div>
</div>
</div>
The click event is linked to the wrong element.
"$('#img')" will point to an "img" id. Your image, however, has the id "item1", so try with $('#item1').click(function(){

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() {
});

Javascript "close button" not working

Today I tried to make the simpliest close button in javaScript. It unfortunately does not work. This is how it look like:
<div id="popup_bg">
<div id="popup_window">
<span id="popup_close">
</span>
</div>
</div>
and the js code is:
<script type=”text/javascript”>
$("#popup_close").click(function() {
$("#popup_bg").fadeOut();
event.stopPropagation();
});
</script>
I'd also like to make it apply to any of those "popups", so I'd probably change my it to something like $(this).parent().parent().fadeOut(); - is it possible to do so?
Thanks for help guys! :)
#EDIT
As none of Your solutions work I'll place my code literally :D Maybe You'll find some mistakes that makes it faulty:
<?php if(isset(errors['user'])) : ?>
<script type="text/javascript">
$(function()
{
$("#popup_close").on('click', function() {
$("#popup_background").fadeOut();
//event.stopPropagation();
});
});
</script>
<div id="popup_background" >
<div class="popup_window">
<span class="title">
error
</span>
<span class="message"><?php echo errors['user']; ?>
</span>
<span id="popup_close" class="button">OK</span>
</div>
</div>
<?php endif; ?>
I hope that will help You spot any errors. It displays correctly, I click on my "OK" span, nothing happens :p I hate js :D
I saw your code, the jquery part of the code is working..
Check here: Jsfiddle -> http://jsfiddle.net/Zahinize/7YD4D/13/
You should rewrite your conditional If statement like this,
<? ini_set('error_reporting', E_ALL); ?>
<script type="text/javascript">
$(function()
{
$("#popup_close").on('click', function() {
$("#popup_background").fadeOut();
//event.stopPropagation();
});
});
</script>
<div id="popup_background" >
<div class="popup_window">
<span class="title">
error
</span>
<span class="message">
<?php
if(isset(errors['user'])){
echo errors['user'];
}
?>
</span>
<span id="popup_close" class="button">OK</span>
</div>
</div>
set error_reporting at that the top..
See more here: http://php.net/manual/en/function.error-reporting.php
Maybe this would help, but frankly i haven't seen error handling like this: error['user'] anywhere.. you should see error handling for writing better code ;)
IDs must unique, you should use classes instead:
<div class="popup_bg">
<div class="popup_window">
<span class="popup_close"></span>
</div>
</div>
Then for selecting the target parent of the clicked element you can use closest method:
$(function() {
$(".popup_close").click(function(event) {
$(this).closest(".popup_bg").fadeOut();
// event.stopPropagation();
});
});
Note that in your code event is undefined you should pass the event object to your handler.
Add document.ready and/or use .on function
<script type=”text/javascript”>
$(function(){
$("#popup_close").on('click', function() {
$("#popup_bg").fadeOut();
event.stopPropagation();
});
});
</script>
Also, ID's may not repeat in your document, use other selector like class
If there are more than one popup better to use class instead of id.
Example.
$(function()
{
$(".popup_close").on('click',(function()
{
$(this).parents("div.popup_bg").fadeOut();
});
});
And html
<div class = "popup_bg">
<div class = "popup_window">
<span class = "popup_close"></span>
</div>
</div>
You need some content in your span or set height and with. Then you will be able to click on it and it will work.
Avoid tricks with parent().parent() this may break if you change your div structure.
As others have said use the jquery document ready (read a tutorial) and use classes not ids if you intend to reuse the code (read a CSS tutorial)...

Categories

Resources