Click not working in any condition - javascript

I have just a simple hyperlink on which when I am trying to add an click() event handler it is not working. I tried, .on(), .live(), .delegate() none of them worked. How can I do it?
I cannot make a fiddle becuase I don't know why my bootstrap.min.css is not getting included in the external resources section.
Please tell me any other way of doing it.
My Code:
HTML:
<div class="navbar nav-fixed-top navbar-inverse" style="min-height: 50px; margin-bottom: 0; box-shadow: 0px 2px 5px #222;">
<!-- Creating a fixed to the top navbar with no bottom margin and a nice little shadow and increasing the height -->
<div class="navbar-inner" style="border-radius: 0;min-height: 50px; ">
<!-- Creating the inner content of navbar and increasng it's height aswell to match the parent's height aswell -->
<div class="container-fluid">
<!-- Main header starts -->
<button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<!-- Small screen collapseable menu starts --> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span>
<!-- The collapseable menu icon(becuase the three `icon-bar` make an icon :P) -->
</button> <a class="brand" href="#"><img src="img/logo.png"
style="height: 25px;" /> </a>
<!-- adding the logo to the header -->
<div class="nav-collapse collapse pull-right">
<!-- div holding collapseable menu's data -->
<ul class="nav">
<!-- creating a list to be created in the collapseable menu -->
<li>Register
</li>
<!-- adding an hyper link to the collapseable menu -->
</ul>
<!-- closing the list -->
</div>
<!-- closing the div holding collapseable menu's data -->
</div>
<!-- closing the main header -->
</div>
<!-- closing inner content holder of navbar div -->
</div>
<!-- closing the fixed to top navbar holder -->
CSS: Using bootstrap.min.css
JS:
var registerBtn = $("#register_button"); //storing the hyperlink of register in a variable
var i = 0; //click count
$(registerBtn).on('click', function (e) {
i++;
if (i % 2 === 0) {
$("#register_frm").fadeToggle('fast', function () {
$("#login_frm").fadeToggle('fast');
});
$("#register").text('Register');
} else {
$("#login_frm").fadeToggle('fast', function () {
$("#register_frm").fadeToggle('fast');
});
$("#register").text('Login');
}
});
Any suggesstions?

Change your code :
$(function() {
var registerBtn = $("#register_button"); //storing the hyperlink of reg....
var i = 0; //click count
registerBtn.on('click', function (e) { // since registerBtn is a reference to anchor tag
e.prevenDefault(); // prevent default behaviour of anchor tag
.........
});
});

It's probably executing the handler binding before the element is created in the DOM. Either move the code to the end of the document (after the element has been created), or wrap it inside a ready event:
$(function() {
var registerBtn = $("#register_button"); //storing the hyperlink of register in a variable
var i = 0; //click count
$(registerBtn).on('click', function (e) {
i++;
if (i % 2 === 0) {
$("#register_frm").fadeToggle('fast', function () {
$("#login_frm").fadeToggle('fast');
});
$("#register").text('Register');
} else {
$("#login_frm").fadeToggle('fast', function () {
$("#register_frm").fadeToggle('fast');
});
$("#register").text('Login');
}
});
});

Related

Dropdown menu opened on pageload ONLY on homepage

I created simple CSS menu with only one dropdown submenu, which has to be opened on pageload ONLY on homepage, and keep it closed by default on rest of site pages.
I managed to set dropdown menu to be opened by default on pageload with Javascript (and closed onclick), and this works perfectly.
<!-- MENU -->
<div class="divBg">
<!-- BUTTON 1 -->
<div class="dropdown">
<button class="dropbtnMain" onclick="document.getElementById('dropdown').style.display=='none' ? document.getElementById('dropdown').style.display='' : document.getElementById('dropdown').style.display ='none';">Dropdown categories</button>
<!-- BUTTON 1 DROPDOWN CONTENT -->
<div class="dropdown-content" id="dropdown">
<a href=#>Dropdown link 1</a>
<a href=#>Dropdown link 2</a>
<a href=#>Dropdown link 3</a>
</div>
</div>
<!-- BUTTON 2 -->
<div class="dropdown">
<button class="dropbtn">Category 2</button>
</div>
<!-- BUTTON 3 -->
<div class="dropdown">
<button class="dropbtn">Category 3</button>
</div>
</div>
But is there solution to have dropdown opened ONLY on homepage, and closed by default on all other pages?
So you can do it by add css class:
.is-hidden {
display: none;
}
and then in JavaScript you can base on page that is loaded:
if (window.location.pathname !== '/') {
document.querySelector('.dropdown').classList.add('is-hidden');
}
If you're using seperate html files you could just remove the javascript?
But I'm guessing, although not specified you're including the dropdown file in your other pages you can use a javascript function with location.pathname, to check what the filename is and only run it then
This as your onclick.
onclick="foo()"
This is the function to go at the top in a script area or script file.
function foo(){
if(location == "http://foobar.com"){
//Code to open your drop down
}
}
something like this.
You can give your body tag a class of 'home' and then add the following CSS.
body.home .dropdown{display:block;}
This should do the trick.
Try this CSS code.
#dropdown
{
display: none;
}
body.home #dropdown
{
display:block;
}
I would add an id and a class to the body like this:
<body id="home" class="home">
...
</body>
And then I would check if body has this selector:
function hasClass(ele, cls) {
return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}
if(hasClass(document.getElementById("home"), "test")){
//do something
}

closing the sidenav by clicking enywhere outside the sidenav

I want to Close the sidenav by clicking anywhere outside sidenav
my html code is
<body>
<!-- show image while loading -->
<div class="se-pre-con"></div>
<!-- Header starts here -->
<div class = "header">
<!-- search bar -->
<?php include("header.php");?>
<!-- search bar ends here -->
</div>
<!-- header ends here -->
<div class="primary" id="primary">
<!-- image slider starts here -->
<div class="image-slider">
<?php include("slider.php");?>
</div>
<!-- image slider starts here -->
<!-- all-content starts here -->
<div class = "container wraper">
<!-- content starts here -->
<div class="content">
<h3 class="Category"><strong> Category </strong>
<button type="submit" class="btn btn-xs btn-success complete" id="more"><strong>More </strong> <span class="glyphicon glyphicon-forward"></button>
</h3><hr id="index-hr">
<?php include("functions/index_category.php"); ?>
</div>
<!-- content ends here -->
</div>
<!-- all-content ends here-->
<!-- daily adds starts here -->
<div class="container news">
<h3 class="news"><strong> Daily News </strong></h3><hr id="index-hr">
</div>
<!-- daily adds ends here -->
<!-- side nav starts here -->
<div id="mySidenav" class="sidenav">
×
<div id="result">
<?php include("functions/sub_category.php")?>
</div>
</div>
<!-- side nav ends here -->
</div>
</body>
The Js i tried :
//close the side nav when clicked outside
var primary = document.getElementById('primary');
var sidenav = document.getElementById('mySidenav');
window.onclick = function(event){
if( event.target == primary ){
sidenav.style.width = "0px";
primary.style.marginLeft = "0px";
}
}
How ever it works clicking enywhere on the side nav by replacing event.target == sidenav But i want to close it by clickng outside
js for opening and closing the side nav are
function openNav() {
if($(window).width() > 600){
$("#mySidenav").attr("style","width:350px");
$(".primary").attr("style","margin-left:350px");
}else{
$("#mySidenav").attr("style","width:100%");
$(".primary").attr("style","margin-left:100%");
}
}
function closeNav() {
$("#mySidenav").attr("style","width:0px");
$(".primary").attr("style","margin-left:0px");
}
css code:
.wraper{
min-height: 165px;
overflow: hidden;
height: 200px;
}
.content {
margin-top: 30px;
}
#more{
width:6%;
margin-right:0px;
float:right;
}
.wraper.complete{
height: auto;
}
h3.sub{
color:#d34615;
text-decoration:underline;
padding-left: 10px;
}
#index-hr{
width:100%;
border-top:1px solid #333;
opacity:0.3;
}
Just check the event.target to see if it was NOT the side nav and that the nav is NOT already open:
//close the side nav when clicked outside
var primary = document.getElementById('primary');
var sidenav = document.getElementById('mySidenav');
window.onclick = function(event){
var sideNavWidth = sidenav.style.width;
// check to see if the event target was not the side nav
// AND that the side nav is open
if( event.target !== sidenav && sideNavWidth !== "0" ){
sidenav.style.width = "0";
primary.style.marginLeft = "0";
}
}
This is a crude implementation of your code, but you can see that the side nav bar does, in fact open (yellow) and will not close if you click on it, but will close if you click anywhere else.
//close the side nav when clicked outside
var primary = document.getElementById('primary');
var sidenav = document.getElementById('mySidenav');
window.onclick = function(event){
var sideNavWidth = sidenav.style.width;
// check to see if the event target was not the side nav
// AND that the side nav is open
if( event.target !== sidenav && sideNavWidth !== "0" ){
closeNav();
}
}
function closeNav(){
sidenav.style.width = "0";
primary.style.marginLeft = "0";
}
.sidenav { background: yellow;}
<div class="primary" id="primary">
<!-- image slider starts here -->
<div class="image-slider">
<?php include("slider.php");?>
</div>
<!-- image slider starts here -->
<!-- all-content starts here -->
<div class = "container wraper">
<!-- content starts here -->
<div class="content">
<h3 class="Category"><strong> Category </strong>
<button type="submit" class="btn btn-xs btn-success complete" id="more"><strong>More </strong> <span class="glyphicon glyphicon-forward"></button>
</h3><hr id="index-hr">
<?php include("functions/index_category.php"); ?>
</div>
<!-- content ends here -->
</div>
<!-- all-content ends here-->
<!-- daily adds starts here -->
<div class="container news">
<h3 class="news"><strong> Daily News </strong></h3><hr id="index-hr">
</div>
<!-- daily adds ends here -->
<!-- side nav starts here -->
<div id="mySidenav" class="sidenav">
×
<div id="result">
<?php include("functions/sub_category.php")?>
</div>
</div>
<!-- side nav ends here -->
</div>

display hidden div after click

I'm currently working on this website.
When I hover over a project in my index, a number appears. I am trying to make it so that number stays there if I click on the project. And then disappears again if I click on a different project.
Right now my code looks something like this:
$('.project').mouseover(function(){
$(this).prev().show()
})
$('.project').mouseout(function(){
$(this).prev().hide()
})
$('.project').click(function(){
$(this).prev().show()
})
HTML:
<!-- Project -->
<div data-accordion>
<!-- Number -->
<div class="number" id="n1">1</div>
<!-- Title -->
<a class="project slide-link" id="p1" data-slide-id="1" data-control>Midi Matilda</a>
<!-- Tags -->
<a class="tag t1">(Identity)</a>
<a class="tag t1">(Music)</a>
<div data-content>
<div class="info">This project is cool.</div>
</div>
</div>
<!-- Project -->
<div data-accordion>
<!-- Number -->
<a class="number" id="n2">2</a>
<!-- Title -->
<a class="project slide-link" id="p2" data-slide-id="2" data-control>The Independent</a>
<!-- Tags -->
<a class="tag t2">(Poster)</a>
<div data-content>
<div class="info">This project is cooler.</div>
</div>
</div>
NEW JQuery:
//$('.project').mouseover(function(){
// $(this).prev().show()
//})
//$('.project').mouseout(function(){
// $(this).prev().hide()
//})
$('.project').click(function(){
var id = $(this).attr("id");
hideOthers(id);
$(this).prev().show();
});
function hideOthers(id){
$('.project').not('#' + id).prev().hide();
}
^The problem here is that the number is no longer visible when hovering over the project. And the number does not go away if I click on the same project title again.
You don't need to use javascript to achieve this, looking at your code (on the website you referenced), once the accordion is open, an open class is set. So you can use css selectors to set the visibility of the numbers like this:
/* Show on hover */
[data-accordion]:hover > .number {display:block}
/* Show when clicked/open */
[data-accordion].open > .number {display:block}
Try this
var flag = false;
$('.project').mouseover(function(){
if(flag == false)
$(this).prev().show()
})
$('.project').mouseout(function(){
if(flag == false)
$(this).prev().hide()
})
$('.project').click(function(){
if(flag == false){
$(this).prev().show()
}else{
$(this).prev().hide()
}
flag = !flag;
})
This gets the id of the clicked element and shows the previous element, while hiding the others.
Hope this helps!
$('.project').click(function(){
var id = $(this).attr("id");
hideOthers(id);
$(this).prev().toggle();
});
function hideOthers(id){
$('.project').not('#' + id).prev().hide();
}
Here is a fiddle

Jquery - Click event doesn't work after resized

I'm doing a responsive menu that check the window.resize event and, when it fits the minimum browser width, a click function for a button is allowed. If the browser width is greater, then the click function is unbound. I need to do this because the same element that is the button on the mobile version, is a visual element on the desktop version.
The problem is that, with the code that I have now, when the page is loaded (desktop or mobile screen), the click function works fine. But, if I resize the browser and click on the element again, it doesn't work. If I want to mobile nav works, I need to refresh the page to make it work. Really annoying.
To help understand what is happening, I've made a simple example. Here's is the simple code (just to check the click function issue)
HTML
<!-- WRAPPER -->
<div id="freakers-wrapper">
<!-- HEADER -->
<header id="header">
<div class="header-bottom">
<div class="container">
<div class="row">
<div class="col-md-5">
<!-- MENU -->
<nav class="menu-wrapper-left">
<a class="menu-trigger" href="#">
<span></span>
</a>
<ul id="main-menu" class="menu menu--main menu--left main-menu">
<li>Home</li>
<li class="has-children">
Shop
<ul class="sub-menu is-hidden">
<li class="go-back">Back</li>
<li>Shop 1</li>
<li>Shop 2</li>
<li>Shop 3</li>
</ul>
</li>
<li><a href="#" >Blog</a></li>
</ul> <!-- end main-menu -->
</nav> <!-- end menu-wrapper -->
</div>
<div class="col-md-2">
<div class="logo">
<a href="#">
<img src="images/logo.png" alt="Logo" class="img-responsive">
</a>
</div>
</div>
<div class="col-md-5">
<!-- MENU -->
<nav class="menu-wrapper-right">
<ul id="main-menu" class="menu menu--main menu--right main-menu">
<li>help</li>
<li>lookbook</li>
<li>model</li>
</ul> <!-- end main-menu -->
</nav> <!-- end menu-wrapper -->
</div>
</div>
</div>
</div> <!-- end header-bottom -->
</header> <!-- end header -->
<!-- MOBILE NAV -->
<div id="mobile-nav"></div>
</div> <!-- end freakers-wrapper -->
JS
(function($) {
"use strict";
$(document).ready(function () {
$(window).on('load resize', function(){
moveNavigation();
});
/* ----------------------------------------------------------------------
Main Menu
---------------------------------------------------------------------- */
//if you change this breakpoint, don't forget to update this value as well
var MqL = 1030,
menuLeft = $('.menu-wrapper-left').html(),
menuRight = $('.menu-wrapper-right').html();
console.log(menuRight);
console.log(menuLeft);
//move nav element position according to window width
// moveNavigation();
//mobile - open lateral menu clicking on the menu icon
$(document).on('click', '.menu-trigger', function(event){
event.preventDefault();
if($('#freakers-wrapper').hasClass('push-content')){
closeNav();
}else{
$('#freakers-wrapper').addClass('push-content');
$('#mobile-nav .menu').addClass('menu--open');
$(this).addClass('nav-is-visible');
}
});
//open submenu
$('.has-children').on('click', function(event){
var selected = $(this);
if( selected.children('ul').hasClass('is-hidden') ) {
selected.children('ul').removeClass('is-hidden');
}
});
//submenu items - go back link
$('.go-back').on('click', function(evt){
evt.stopPropagation();
$(this).parent('ul')
.addClass('is-hidden')
.parent('.has-children')
.parent('ul');
});
function closeNav(){
$('#freakers-wrapper').removeClass('push-content');
$('.menu--main').removeClass('menu--open');
$('.has-children ul').addClass('is-hidden');
}
function checkWindowWidth() {
//check window width (scrollbar included)
var e = window,
a = 'inner';
if (!('innerWidth' in window )) {
a = 'client';
e = document.documentElement || document.body;
}
if ( e[ a+'Width' ] >= MqL ){
closeNav();
if ( $('.menu-trigger').hasClass('menu-trigger-open') ){
$('.menu-trigger').removeClass('menu-trigger-open');
}
return true;
} else {
var menuElm = $('.main-menu .has-children');
if($('.sub-menu ul', menuElm).hasClass('left-menu')){
$('.sub-menu ul', menuElm).removeClass('left-menu');
}
return false;
}
}
function moveNavigation(){
var navigation = $('.menu--main'),
desktop = checkWindowWidth();
if ( desktop ) {
$('#mobile-nav').children().remove();
$('.menu-wrapper-left').html(menuLeft);
$('.menu-wrapper-right').html(menuRight);
} else {
navigation.appendTo('#mobile-nav');
$('.menu--main').not(':first').remove().children('li').appendTo('.menu--main:first');
}
}
$(".menu-trigger").click(function() {
$(this).toggleClass("menu-trigger-open");
});
});
}(jQuery));
If you want to see it in action, I've made a Codepen (try resize to see it working)
http://codepen.io/thehung1724/full/JYmzWr/
I hope I could explain well my problem. I've searched and didn't found a solution for this issue (or maybe I just didn't know really well what to look for). Although when you resize the screen, you can still click on the menu icon, but please notice it doesn't transform to 'X' letter and you can't click to show sub-menu
Works
Doesn't work
Any help would be appreciated!
An easy fix would be to replace
$('.has-children').on('click', function(event){
with
$(document).on('click', '.has-children', function (event) {
When you clone the nav from one place to another you are losing the pointer to the on click function for .has-children
With the $(document).on.... you're actually binding the function to the document which doesn't get disposed.
Update:
Replace the following section of javascript
$('.has-children').on('click', function (event) {
var selected = $(this);
if (selected.children('ul').hasClass('is-hidden')) {
selected.children('ul').removeClass('is-hidden');
}
});
$('.go-back').on('click', function (evt) {
evt.stopPropagation();
$(this).parent('ul').addClass('is-hidden').parent('.has-children').parent('ul');
});
With
$(document).on('click', '.has-children', function (event) {
var selected = $(this);
if (selected.children('ul').hasClass('is-hidden')) {
selected.children('ul').removeClass('is-hidden');
}
});
$(document).on('click', '.go-back', function (evt) {
evt.stopPropagation();
$(this).parent('ul').addClass('is-hidden').parent('.has-children').parent('ul');
});
Further update:
I've Forked your code in CodePen with the above changes: http://codepen.io/anon/pen/JYmVXm

How to add closing button script

I am using Multi Level Push menu and trying to add a button to make it close.
Basic HTML:
<div class="container">
<!-- Push Wrapper -->
<div class="mp-pusher" id="mp-pusher">
<!-- mp-menu -->
<nav id="mp-menu" class="mp-menu">
<div class="mp-level">
<a class="icon icon-star" href="#" onclick="closeMe();" id="linkk">Exit</a>
</div>
</nav>
<div class="scroller"><!-- this is for emulating position fixed of the nav -->
<div class="scroller-inner">
<!-- Top Navigation -->
<div>Button</div>
</div><!-- /scroller-inner -->
</div><!-- /scroller -->
</div><!-- /pusher -->
</div><!-- /container -->
JS:
new mlPushMenu( document.getElementById( 'mp-menu' ), document.getElementById( 'trigger' ) );
function closeMe(){
var container = document.getElementById( 'mp-pusher'; );
classie.remove( container, 'mp-pushed'; );
scrollToAnchor('#link');
};
Here is a working fiddle:
http://jsfiddle.net/xs1j8kq5/3/
I am using external resources, of course. The above code for the exit button does not function properly.
How can I close the sidebar menu, and if possible, scroll to an anchor point somewhere on the site?
First fix your code as i mentioned in my comment. There are several syntax errors. And define closeMe before your you call it. Now scrollToAnchor not works, define that before closeMe also.
Now, when you clicked the Exit it's not animated, but i think, now you can figure out what to do with it to animate. http://jsfiddle.net/xs1j8kq5/22/
<script type="text/javascript">
function closeMe() {
var container = document.getElementById('mp-pusher');
classie.remove(container, 'mp-pushed');
classie.remove(container, 'mp-pusher');
container.style.transform = "translate3d(+300px, 0px, 0px)";
//scrollToAnchor('#services');
}
;
</script>
<div class="container">
<!-- Push Wrapper -->
<div class="mp-pusher" id="mp-pusher">
<!-- mp-menu -->
<nav id="mp-menu" class="mp-menu">
<div class="mp-level">
<a class="icon icon-star" href="#" onclick="closeMe();" id="linkk">Exit</a>
</div>
</nav>
<div class="scroller"><!-- this is for emulating position fixed of the nav -->
<div class="scroller-inner">
<!-- Top Navigation -->
<div>Button</div>
</div><!-- /scroller-inner -->
</div><!-- /scroller -->
</div><!-- /pusher -->
</div><!-- /container -->
For scroll, you need to define an <a name="services"></a> tag where you want to scroll.
edit: working fiddle:
http://jsfiddle.net/xs1j8kq5/24/
As you mentioned jQuery in your tags, here is a shorter jQuery equivalent of your code (which does not require an attribute-based event handler):
new mlPushMenu($('#mp-menu')[0], $('#trigger')[0]);
$(function () {
$('#linkk').click(function(e) {
e.preventDefault(); // Stop any scrolling to the bookmark link
classie.remove($('#mp-pusher'));
classie.remove($('#mp-pushed'));
scrollToAnchor('#services');
});
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/xs1j8kq5/23/
You have to define your 'trigger' when you instantiate 'mlPushMenu'
So, just state:
new mlPushMenu( document.getElementById( 'mp-menu' ),
document.getElementById( 'trigger' ) )
replacing the id of your button.
In this particular case use 'linkk':
new mlPushMenu( document.getElementById( 'mp-menu' ),
document.getElementById( 'linkk' ) )
You could use a class, and affect as many 'a's as you want:
new mlPushMenu(document.getElementById('mp-menu'),
document.getElementsByClassName('menu-trigger'));

Categories

Resources