jQuery click event happening on parent DIV when using stopPropagation - javascript

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
jQuery(document).ready(function() {
//Add Header Listeners
//Signup Listener
jQuery(".top-nav-login-links .exchange-signup").click(headerObject.toggleLightBoxSignup.bind(headerObject));
//Login Listener
jQuery(".top-nav-login-links .exchange-login").click(headerObject.toggleLightBoxLogin.bind(headerObject));
//Lightbox Close Listeners
jQuery("i.close-lightbox, div.light-box-parent").click(function(e) {
e.stopPropagation();
if(jQuery(this).attr("data-rel") == "signUpVisible") {
headerObject.toggleLightBoxSignup();
} else if(jQuery(this).attr("data-rel") == "loginVisible") {
headerObject.toggleLightBoxLogin();
}
});
});
var headerObject = {
isLoginLightBoxVisible : false,
isSignupLightBoxVisible : false,
isCookiesBannerVisible : true,
showServicesDropdown : false,
isMobileMenuVisible : false,
layoutElement : document.querySelector('#layout'),
toggleLightBoxLogin : function() {
jQuery("#loginVisible").toggle();
},
toggleLightBoxSignup : function() {
jQuery("#signUpVisible").toggle();
},
toggleMobileMenu : function() {
if (!this.isMobileMenuVisible) {
this.layoutElement.classList.add("active");
} else {
this.layoutElement.classList.remove("active");
}
this.isMobileMenuVisible = !this.isMobileMenuVisible;
},
closeCookiesBanner : function() {
this.isCookiesBannerVisible = false;
//localStorage.setItem('this.isCookiesBannerVisible', 'false');
},
onMenuItemClick : function() {
if (('ontouchstart' in window) || window["DocumentTouch"] && document instanceof DocumentTouch) {
event.preventDefault();
event.stopPropagation();
}
}
};
</script>
<div class="top-nav-login-links">
<ul>
<li class="pure-hidden-phone"><a class="exchange-signup" href="#">Sign up</a></li>
<li class="pure-hidden-phone"><a class="login exchange-login" href="#">Log in</a></li>
<li class="pure-hidden-tablet pure-hidden-desktop" data-ng-click="viewModel.toggleLightBoxLogin()"><i class="fa fa-user login-cta login"></i></li>
</ul>
</div>
</div>
</section>
<div id="loginVisible" class="light-box-parent login-lightbox" data-rel="loginVisible">
<div class="light-box-options">
<div class="light-box-container" >
<figure class="login-figure">
<a id="link-expert-login" href="http://experts.blurgroup.com/">
<img id="img-login-expert" src="<?php echo get_template_directory_uri(); ?>/images/shared/login_expert_logo.png" alt="Expert">
<figcaption class="login-figcaption">Expert</figcaption>
</a>
</figure>
<figure class="login-figure customer-login">
<a id="link-customer-login" href="/customer/">
<img id="img-login-customer" src="<?php echo get_template_directory_uri(); ?>/images/shared/login_customer_logo.png" alt="Customer">
<figcaption class="login-figcaption">Customer</figcaption>
</a>
</figure>
</div>
<div class="light-box-title">Login</div>
<i class="fa fa-times-circle"></i>
</div>
</div>
<div id="signUpVisible" class="light-box-parent expert-sign-up" data-rel="signUpVisible">
<div class="light-box-options">
<div class="light-box-container">
test
</div>
<div class="light-box-title">New to blur Group? Join the crowd</div>
<i class="fa fa-times-circle close-lightbox" data-rel="signUpVisible"></i>
</div>
</div>
I am currently implementing some lightboxes which open on certain anchor ticks being click. I then have the functionality whereas when the lightbox itself or an icon within it (with the class 'close' is clicked) it should close the appropriate lightbox according to the value stored in a 'data-rel' HTML5 data attribute.
The problem I am having is that the click event is propagating to any child element within the lightbox, even when I have targeted the specific elements themselves and used event.stopPropagation().
I can't figure out why this is happening. Can someone see a problem with my code?
Thanks

Try using stopImmediatePropagation function in place of stopPropagation

Related

Vue.js - how to hide an image with the hover event on it and show another?

I have two images whose behavior I want to see next.
By default the image will be shown with the name 'home' and with the event 'mouseover' I want to hide and show the image with the name 'blackhome'.
I have the two images shown on screen and there's nothing happens with the mouse events
I don't know if this is possible.
Here's a codepen link with the issue
https://codepen.io/CharlieJS/pen/gOrayzW
this is my template
<li class="nav-item" #mouseover="homeLink = !homelink" #mouseleave="!homeLink" >
<a class='nav-link home' href="https://www.google.com/">
<img v-if="homeLink" class="logo" src="../../assets/home.png">
<img v-if="!homelink" src="../../assets/blackhome.png">
</a>
</li>
and my script
export default {
data: function () {
return {
homeLink: false
}
},
computed: {
auth () {
return this.$store.getters.isAuthenticated
}
},
methods: {
onLogout() {
this.$store.dispatch('logout')
},
}
}
</script>
Thank you in advance for your time and help
Try v-if and v-else as follows :
<li class="nav-item" #mouseover="homeLink = !homelink" #mouseleave="homeLink=false" >
<a class='nav-link home' href="https://www.google.com/">
<img v-if="homeLink" class="logo" src="../../assets/home.png"/>
<img v-else src="../../assets/blackhome.png"/>
</a>
</li>
let app = new Vue({
el: "#app",
data: function() {
return {
homeLink: false
}
},
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app">
<li class="nav-item" #mouseover="homeLink = !homelink" #mouseleave="homeLink=false">
<a class='nav-link home' href="https://www.google.com/">
<img v-if="homeLink" class="logo" src="https://picsum.photos/300/200?image=244" />
<img v-else src="https://picsum.photos/300/200?image=1024" />
</a>
</li>
</div>

jquery hide method hides div but then div reappears

I have the following code where I want to hide the closest grouping div. When I click the delete button, the div disappears but then comes back (added 600 so I could see this).
I have researched and found others saying to use event.preventDefault, return false; and add href”#!’ to the <a> tag. None seem to work. I changed the .hide() to .remove() and It works, but I won't just want to hide the div and use it later in the post model binding
#model Durendal.Core.ViewModels.RoleViewModel
<div class="d-flex flex-row grouping">
<div class="flex-grow-1" style="overflow-x: auto;">
#(Html.Kendo().DropDownListFor(m => m.Id)
.DataTextField("Name")
.DataValueField("Id")
.MinLength(3)
.HtmlAttributes(new { style = "width:100%;" })
.Height(290)
.Filter(FilterType.Contains)
.AutoWidth(true)
.DataSource(source =>
{
source.Custom()
.Transport(transport => transport
.Read(read => read
.Action("GetRoles", "DataApi", new { Area = "Shared" })));
})
)
</div>
<div class="">
<a href="#!" class="btn btn-sm btn-outline-danger waves-effect remove-grouping-button">
<i class="fas fa-times"></i>
</a>
</div>
<script type="text/javascript">
(function () {
$('.remove-grouping-button').click(function (event) {
event.preventDefault();
$(this).closest('.grouping').hide(600);
return false;
});
})();
</script>
</div>
This should hide the div but it reappears
Your code works - some other code must make it re-appear.
I only post this for demonstration and will delete it when you have seen it.
Please do not vote up or accept as answer and No need to vote down either
$(function() {
$('.remove-grouping-button').click(function(event) {
event.preventDefault(); // cancel anchor click
$(this).closest('.grouping').hide(600);
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<div class="d-flex flex-row grouping">
<div class="flex-grow-1" style="overflow-x: auto;">
Some Kendo dropdown
</div>
<div class="">
<a href="#!" class="btn btn-sm btn-outline-danger waves-effect remove-grouping-button">
<i class="fas fa-times"></i>
</a>
</div>
</div>

Change the onclick of a hyper link

I want to update the click event of the hyperlink onClick and want to update the html inside the hyperlink in jquery
HTML
<a class=" save" href="javascript:void(0);" onclick="save_unsave('unsave','UID','ID',this);">
<div class="jopt_iconwrap" title="Unsave" alt="Unsave" >
<span class="saved"></span>
</div>
Unsave
</a>
Now onlick of save_unsave function i want to update the html design as below:
<a class=" save" href="javascript:void(0);" onclick="save_unsave('save','UID','ID',this);">
<div class="jopt_iconwrap" title="Save" alt="Save" >
<span class=""></span>
</div>
Save
</a>
I am trying to do this in the function:
jQuery
if(type == 'save')
{
var new_type = "'unsave'";
jQuery(elem_obj).html("");
jQuery(elem_obj).html('<a onclick="save_unsave('+new_type+','+uid+','+id+',this);" class="saved" href="javascript:void(0);"><div class="jopt_iconwrap" title="Unsave" alt="Unsave"><span class="saved"></span></div>Unsave</a>');
}
else if(type == 'unsave')
{
var new_type = "'save'";
jQuery(elem_obj).html("");
jQuery(elem_obj).html('<a onclick="save_unsave('+new_type+','+uid+','+id+',this);" class=" save" href="javascript:void(0);"><div class="jopt_iconwrap" title="Unsave" alt="Unsave"><span class="mico"></span></div>Save</a>');
}
How can we do this in jquery.Please help me in the i have the elmenet object in the function.
simply i will suggest you to use replaceWith() in place of .html() it will work properly for you.
$('a').click(function() {
if ($(this).hasClass('save')) {
$(this).removeClass('save').addClass('unsave');
$(this).text('Unsave')
$(this).attr('id','save')
} else {
$(this).removeClass('unsave').addClass('save');
$(this).text('Save')
$(this).attr('id','unsave')
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a class=" save">
<div class="jopt_iconwrap" title="Save" alt="Save">
<span class=""></span>
</div>
Save
</a>
Try this way
You can replace the onclick event, like this:
$('.save')[0].onclick = function() {
save_unsave('save', 'UID', 'ID', this);
}

Response menu not collapsing and reloads page

At http://www.dentalo.se/contact it is using a responsive menu for mobile devices.
When clicking on the menu button it collapses the menu but the same time reloads the page.
Can anyone tell my why and how I can fix it?
Thanks for the time you are taking to help me.
Edit
HTML
<div class="container">
<div class="navbar-header">
<!-- BEGIN RESPONSIVE MENU TOGGLER -->
<button type="button" class="navbar-toggle btn navbar-btn" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<!-- END RESPONSIVE MENU TOGGLER -->
<!-- BEGIN LOGO (you can use logo image instead of text)-->
<a class="navbar-brand logo-v1" href="/">
<img src="/assets/img/logo_blue.png" id="logoimg" alt="">
</a>
<!-- END LOGO -->
</div>
<!-- BEGIN TOP NAVIGATION MENU -->
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li id="MainMenuHome">Start</li>
<li class="dropdown" id="MainMenuDentalo">
<a class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-delay="0" data-close-others="false" href="#">
Dentalo
<i class="icon-angle-down"></i>
</a>
<ul class="dropdown-menu">
<li id="SubMenuAbout">Om Dentalo</li>
<li id="SubMenuJob">Lediga tjänster</li>
<li id="SubMenuConnect">Anslut</li>
</ul>
</li>
<li id="MainMenuLogIn">Logga in</li>
<li id="MainMenuContact">Kontakt</li>
<li class="menu-search">
<span class="sep"></span>
<i class="icon-search search-btn"></i>
<div class="search-box">
<form action="#">
<div class="input-group input-large">
<asp:TextBox runat="server" placeholder="Sök..." CssClass="form-control" ID="textBoxSearch"></asp:TextBox>
<span class="input-group-btn">
<asp:Button runat="server" CssClass="btn theme-btn" ID="ButtonSearch" OnClick="ButtonSearch_Click" Text="Sök" />
</span>
</div>
</form>
</div>
</li>
</ul>
</div>
<!-- BEGIN TOP NAVIGATION MENU -->
</div>
JavaScript
/*
* Project: Twitter Bootstrap Hover Dropdown
* Author: Cameron Spear
* Contributors: Mattia Larentis
*
* Dependencies?: Twitter Bootstrap's Dropdown plugin
*
* A simple plugin to enable twitter bootstrap dropdowns to active on hover and provide a nice user experience.
*
* No license, do what you want. I'd love credit or a shoutout, though.
*
* http://cameronspear.com/blog/twitter-bootstrap-dropdown-on-hover-plugin/
*/
;(function($, window, undefined) {
// outside the scope of the jQuery plugin to
// keep track of all dropdowns
var $allDropdowns = $();
// if instantlyCloseOthers is true, then it will instantly
// shut other nav items when a new one is hovered over
$.fn.dropdownHover = function(options) {
// the element we really care about
// is the dropdown-toggle's parent
$allDropdowns = $allDropdowns.add(this.parent());
return this.each(function() {
var $this = $(this),
$parent = $this.parent(),
defaults = {
delay: 500,
instantlyCloseOthers: true
},
data = {
delay: $(this).data('delay'),
instantlyCloseOthers: $(this).data('close-others')
},
settings = $.extend(true, {}, defaults, options, data),
timeout;
$parent.hover(function(event) {
// so a neighbor can't open the dropdown
if(!$parent.hasClass('open') && !$this.is(event.target)) {
return true;
}
if(shouldHover) {
if(settings.instantlyCloseOthers === true)
$allDropdowns.removeClass('open');
window.clearTimeout(timeout);
$parent.addClass('open');
}
}, function() {
if(shouldHover) {
timeout = window.setTimeout(function() {
$parent.removeClass('open');
}, settings.delay);
}
});
// this helps with button groups!
$this.hover(function() {
if(shouldHover) {
if(settings.instantlyCloseOthers === true)
$allDropdowns.removeClass('open');
window.clearTimeout(timeout);
$parent.addClass('open');
}
});
// handle submenus
$parent.find('.dropdown-submenu').each(function(){
var $this = $(this);
var subTimeout;
$this.hover(function() {
if(shouldHover) {
window.clearTimeout(subTimeout);
$this.children('.dropdown-menu').show();
// always close submenu siblings instantly
$this.siblings().children('.dropdown-menu').hide();
}
}, function() {
var $submenu = $this.children('.dropdown-menu');
if(shouldHover) {
subTimeout = window.setTimeout(function() {
$submenu.hide();
}, settings.delay);
} else {
// emulate Twitter Bootstrap's default behavior
$submenu.hide();
}
});
});
});
};
// helper variables to guess if they are using a mouse
var shouldHover = false,
mouse_info = {
hits: 0,
x: null,
y: null
};
$(document).ready(function() {
// apply dropdownHover to all elements with the data-hover="dropdown" attribute
$('[data-hover="dropdown"]').dropdownHover();
// if the mouse movements are "smooth" or there are more than 20, they probably have a real mouse
$(document).mousemove(function(e){
mouse_info.hits++;
if (mouse_info.hits > 20 || (Math.abs(e.pageX - mouse_info.x) + Math.abs(e.pageY - mouse_info.y)) < 4) {
$(this).unbind(e);
shouldHover = true;
}
else {
mouse_info.x = e.pageX;
mouse_info.y = e.pageY;
}
});
});
// for the submenu to close on delay, we need to override Bootstrap's CSS in this case
var css = '.dropdown-submenu:hover>.dropdown-menu{display:none}';
var style = document.createElement('style');
style.type = 'text/css';
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
$('head')[0].appendChild(style);
})(jQuery, this);
It appears that your button element (navbar-btn) is submitting your form. Try adding type="button" to the button element.
Also in the click event handler you can also try to add e.preventDefault() to your click event handler.
I cant seem to find the JavaScript from the click event of your button so I can help much more. If this does not work, please edit your question to show the relevant HTML and JavaScript sections.

Jquery on('click') not firing after first click

I have some HTML:
<div class="post-container self">
<a href="/user/Wiz">
<img class="avatar" alt="Profile Picture" src="">
</a>
<div class="post-body">
<div class="post" style="margin-left:0px;">
<div class="post-timestamp" style="display:inline-block;float:right">
Oct 31
</div>
<div class="post-functions dropdown displaynone" style="float:right;margin-right:5px;">
<a class="dropdown-toggle" data-toggle="dropdown" href="javascript:void(0)">
<i class="icon-cog">
</i>
</a>
<ul class="dropdown-menu post-dropdown" role="menu" aria-labelledby="dLabel">
<a class="post-delete" href="javascript:void(0)"><i class="icon-trash"> </i>Delete</a>
</ul>
</div>
</div>
</div>
</div>
And with that, I have some Jquery:
$('.posts-content').on('click', '.post-delete', function(e) {
$('.post-dropdown').dropdown();
if (confirm('Are you sure you want to delete this post?')) {
var $this = $(this);
$.ajax({
url: '/a/delete_post',
type: 'POST',
dataType: 'json',
data: {'p' : post_id},
success: function() {
//...
return true;
}
});
}
return false;
});
Everything works perfectly the first click, but if I go to another post, and try to click .post-delete, the event never fires, and nothing shows up in the console. It also works if I use $.click(), but I need to dynamically create elements. Why does the $.on('click') not fire the second click?
My guess is that dropdown plugin you use change the DOM structure.
$('.post-dropdown').dropdown();
BTW,
$this.parent().parent().parent().parent().parent() this is really really bad practice.
You should use closest instead.
If you are dynamically creating elements try:
$(document).on('click', '.post-delete', function(e) { });

Categories

Resources