Issue with jQuery : Click event & Switching between "active" elements - javascript

OK, here's my issue and I bet it'll be super-easy for you (I guess it wasn't... lol).
So, let's say I'm having several divs. Once the user clicks on one of them, I want to highlight just this one. In a few words : a) remove (if exists) a specific class from all divs, b) add it to the div being clicked.
And here's the full code...
index.html
<!DOCTYPE html>
<html style='min-height:0px;'>
<head>
<title>Page Title</title>
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1">
<link rel="stylesheet" href="jquery.mobile.min.css" />
<link rel="stylesheet" href="custom.css" />
<script src="jquery.min.js"></script>
<script src="jquery.mobile.min.js"></script>
</head>
<body>
<div data-role="page">
</div>
<script src="custom.js"></script>
</body>
</html>
custom.js
$(function() {
$("div").click( function() {
$("div").removeClass("msp-selected");
$(this).addClass("msp-selected");
});
});
custom.css
media screen and (orientation: portrait) {
.ui-mobile, .ui-mobile .ui-page {
min-height: 420px;
}
}
media screen and (orientation: landscape) {
.ui-mobile, .ui-mobile .ui-page {
min-height: 300px;
}
}
div {
outline:0;
}
div:hover {
outline-width:1px;
outline-color:red;
outline-style: dotted;
overflow:hidden;
}
.msp-selected {
outline-width:1px;
outline-color:red;
outline-style: solid;
}
P.S.
The situation may not be as simple as it initially seemed. I'm using jQuery 1.8.2 and jQuery Mobile 1.3.2. And the actual page is running inside a Webview, itself inside a Cocoa/OS X app. Quite complicated, huh? lol
I can't see any error (not easy to have access to a console that... doesn't exist...). The only thing that I noticed is that when I remove the removeClass part, it does work. Adding it, seems to make the whole thing a mess.

$(function() {
$('div').on( "click", function() {
$(this).addClass('msp-selected');
$(this).siblings().removeClass('msp-selected');
})

Try something like:
$(".box").click( function() {
if($(".activeBox").length > 0) { //check if there is an activeBox element
$(".activeBox").removeClass("activeBox"); //if there is, remove it
}
$(this).addClass("activeBox"); //make the clicked div the activeBox
});
.box and .activeBox classes to be replaced by your own inactive and active selectors as you want.
Here's a jsFiddle example
Update:
With the new HTML, I got this working as a jsFiddle
Here's the code:
HTML within jsFiddle's existing head/body tags:
<div data-role="page">
</div>
CSS from OP:
div {
outline:0;
}
div:hover {
outline-width:1px;
outline-color:red;
outline-style: dotted;
overflow:hidden;
}
.msp-selected {
outline-width:1px;
outline-color:red;
outline-style: solid;
}
jQuery:
$("div").click( function() {
if($(".msp-selected").length > 0) {
$(".msp-selected").removeClass("msp-selected");
}
$(this).addClass("msp-selected");
});
I tested this with the various versions of jQuery available back to 1.7.2 and mobile 1.1.1, with the class being added on click each time. My only suggestion if this still doesn't work is to encase the whole thing in $(document).ready( function() { //click function }); or switch to $("div").on("click", function() {});

Related

mobile tap event issue

I am facing issue with tap event on mobile devices.
create 3 divs with same height. Tap on second div to hide the first div and it will trigger the event on third div.
sample code: reproducible in chrome device simulator
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>phone issue</title>
</head>
<style type="text/css">
.hide {
display: none;
}
#one, #two, #three {
width: 100%;
height: 150px;
border: 1px solid #000;
}
</style>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#two').on('tap', function () {
$('#one').toggle();
});
$('#three').on('tap', function () {
alert('you just clicked me!');
});
});
</script>
<body>
<div id="one">hide</div>
<div id="two">main</div>
<div id="three">click</div>
</body>
</html>
try to use 'click' event instead of 'tap' event. I run in to the same issue and manage to solve it by using 'click' event. Please see jquery mobile documentation for details: https://api.jquerymobile.com/vclick/. Regards.

.slideDown Not Working For ME

So I've managed to link my index.html to jquery but for some reason my .slideDown code is not working. Is there something wrong with it or did I not attach jquery correctly?
Here is my html code (containing the code for .slideDown):
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>TEST</title>
<link rel="shortcut icon" href="../Pictures/Logo.png" />
<link rel="stylesheet" href="stylesheet.css" type="text/css" />
<script src="jquery-2.1.1.min.js"></script>
</head>
<body>
<script>
$("#teamalpha").mouseover(
function(){
$("#teamalpha > div").slideDown(400);
});
</script>
<div id="teamalpha">
<div>
<p>AlphaGuardian</p>
<p>Owner</p>
</div>
</div>
</div>
</body>
</html>
And Here is my CSS code (stylesheet linked correctly):
#teamalpha{
font-family:Optimus;
font-size:24px;
text-align:center;
border:solid;
border-color:#000;
width:250px;
height:250px;
position:relative;
top:100px;
left:200px;
cursor:pointer;
z-index:5;
}
#teamalpha div{
position:relative;
top:-50px;
height:100px;
display:none;
width:250;
background-color:#f7931e;
z-index:6;
}
Your <script> needs to be surrounded by
// Fire on document ready event
$(document).ready(function(){
// some code here
});
OR
// Fire on window load event
$(window).load(function() {
// some code here
});
So it should look like this:
<script>
// Fire on document ready event
$(document).ready(function() {
$("#teamalpha", this).on("mouseover", function() {
$(this).children("div").slideDown(400);
});
});
</script>
OR
// Fire on document ready event
$(window).load(function() {
$("#teamalpha", this).on("mouseover", function() {
$(this).children("div").slideDown(400);
});
});
Your script was running before the page was fully loaded. Now, it'll wait till the document or the window finish loading.
I made a pen with code that worked: http://codepen.io/KK4OXJ/pen/Eagjax/
Basically, you can't fade something in that's hidden with CSS, so we need this:
$('#teamalpha div').hide();
to hide it, instead of using CSS to hide it. It needs to go right before the mousover thing, and we also need to remove the display: none; line in the CSS.
I hope this helps :)

Click Element isn't showing/hiding properly

I have an issue with my code, I'm trying to create a function to hide and show a div
and it's working, but it dosnt work at first, It works only on the second click, so i have to click the link first to get it to start working properly, how can i fix it so that it works on first click?
more info:
im trying to have a div appear and then disapear usin the display and hide functions, the catch is i also want it to disapper when im outside of the div, if its visible, its all working but the problem is when i first load the page thn click the link to display the div, it dosnt appear, only when i click it a second time does it appear. this is the problem i want to fix
this is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
<!-- Bootstrap -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="js/jquery.foggy.min.js"></script>
<style>
body {
background: black;
background-repeat: no-repeat;
background-attachment: fixed;
background-position: center;
background-size: 100%;
color: white;
font-family: 'Segoe UI';
font-size: 24px;
}
.box
{
width: 100%;
margin: auto;
top: 0px;
left: 20%;
right: 0px;
bottom: 0px;
background-color: white;
opacity: 0.4;
position: fixed;
overflow-y: scroll;
overflow-x: scroll;
}
</style>
</head>
<body>
<script lang="en" type="text/javascript">
$(document).ready(function () {
});
$(document).mouseup(function (e) {
var container = $("#boxwrapper");
if (!container.is(e.target) && container.has(e.target).length === 0) {
if (container.is(':visible'))
Hide();
}
});
function Display() {
$("#boxwrapper").show();
$("#boxwrapper").addClass("box");
$("#main").foggy();
}
function Hide() {
$("#boxwrapper").hide();
$("#main").foggy(false);
}
</script>
<div id="main">
Display Div
</div>
<div id="boxwrapper">
</div>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
</body>
</html>
Why don't you use click() method insead of mouseup()?
$('a').click(function (e) {
var container = $("#boxwrapper");
if (container.is(':visible')) {
Hide();
} else {
Display();
}
return false;
});
If you don't want to bind this event to every <a> on your site, add class to your element and bind click to this class. E.g.:
Display Div
and then in your script:
$('a.divToggle').click(function (e) { });
See this working fiddle
JavaScript
function display() {
if ($('#boxwrapper ').css('display') === 'none') {
$('#boxwrapper').show();
} else {
$('#boxwrapper').hide();
}
}
The issue could be a whitespace or anything, since is very hard to reproduce it, but here some advices or things that could be causing the issue:
Organize your code
First of all, you need to organize your code and load the JS libraries at the end of the file or wrap your functions inside the $(document).ready.
If you are using jQuery already, why to use the onClick event on the element itself if you can do it with jQuery.
Instead of all code inside the document mouseUp event, you could just add display: none in the css to #boxwrapper.
Instead of Hide() and Show() functions, you could just use toogleClass('box') jquery function
Difference between Click and MouseUp events
With a mouseup event, you can click somewhere else on the screen, hold down the click button, and move the pointer to your mouseup element, and then release the mouse pointer. A click event requires the mousedown and mouseup event to happen on that element.
Prevent Default Maybe?
You are not preventing Default on your click event. You can do it like:
Display Div

How do I make <a> tags with a class unclickable?

I have some parent nav items with children and I don't need the parent items to be clickable.
They look like this:
Parent Item
Is there anyway to target the <a> tags with the specific class of .parent and make them unclickable?
If anyone interested in Pure CSS solution (As this question is tagged as CSS) than you can use pointer-events: none;
a[href="parent"] {
cursor: default;
pointer-events: none;
}
Demo
As far as support goes
Credits: Mozilla Developer Network
Use:
$(function () {
$('a.parent').on("click", function (e) {
e.preventDefault();
});
});
If you want to avoid using the jQuery library, it's just as easy without it:
var disabled = document.querySelector('.parent');
disabled.addEventListener('click', function(e) {e.preventDefault();}, false);
Another pure CSS option would be to overlay the link with an absolutely positioned "cover":
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style media="all">
.parent {position: relative; z-index: -1;}
.parent:after {content: ""; position: absolute; top:0; right: 0; bottom: 0; left: 0;}
</style>
</head>
<body>
Disabled Link
Normal Link
</body>
</html>
Instead of a listener on every .parent, you can put a single listener on the body. The following will work in every browser in use without any library support:
function stopClickOnParentClass(evt) {
var el = evt.target || evt.srcElement;
if (/(^|\s)parent(\s|$)/.test(el.className)) {
evt.preventDefault();
return false;
}
}
then:
<body onclick="stopClickOnParent(event);" …>
You could also make the class dynamic by passing it to the function and building the regular expression from it.

jQuery hover and class selector

I wan't to change the background color of a div dynamicly using the following HTML, CSS and javascript.
HTML:
<div id="menu">
<div class="menuItem"><a href=#>Bla</a></div>
<div class="menuItem"><a href=#>Bla</a></div>
<div class="menuItem"><a href=#>Bla</a></div>
</div>
CSS:
.menuItem{
display:inline;
height:30px;
width:100px;
background-color:#000;
}
Javascript:
$('.menuItem').hover( function(){
$(this).css('background-color', '#F00');
},
function(){
$(this).css('background-color', '#000');
});
EDIT: I forgot to say that I had reasons not to want to use the css way.
And I indeed forgot to check if the DOM was loaded.
Your code looks fine to me.
Make sure the DOM is ready before your javascript is executed by using jQuery's $(callback) function:
$(function() {
$('.menuItem').hover( function(){
$(this).css('background-color', '#F00');
},
function(){
$(this).css('background-color', '#000');
});
});
I would suggest not to use JavaScript for this kind of simple interaction. CSS is capable of doing it (even in Internet Explorer 6) and it will be much more responsive than doing it with JavaScript.
You can use the ":hover" CSS pseudo-class but in order to make it work with Internet Explorer 6, you must use it on an "a" element.
.menuItem
{
display: inline;
background-color: #000;
/* width and height should not work on inline elements */
/* if this works, your browser is doing the rendering */
/* in quirks mode which will not be compatible with */
/* other browsers - but this will not work on touch mobile devices like android */
}
.menuItem a:hover
{
background-color:#F00;
}
This can be achieved in CSS using the :hover pseudo-class. (:hover doesn't work on <div>s in IE6)
HTML:
<div id="menu">
<a class="menuItem" href=#>Bla</a>
<a class="menuItem" href=#>Bla</a>
<a class="menuItem" href=#>Bla</a>
</div>
CSS:
.menuItem{
height:30px;
width:100px;
background-color:#000;
}
.menuItem:hover {
background-color:#F00;
}
test.html
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>jQuery Test</title>
<link rel="stylesheet" type="text/css" href="test.css" />
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<div id="menu">
<div class="menuItem"><a href=#>Bla</a></div>
<div class="menuItem"><a href=#>Bla</a></div>
<div class="menuItem"><a href=#>Bla</a></div>
</div>
</body>
</html>
test.css
.menuItem
{
display: inline;
height: 30px;
width: 100px;
background-color: #000;
}
test.js
$( function(){
$('.menuItem').hover( function(){
$(this).css('background-color', '#F00');
},
function(){
$(this).css('background-color', '#000');
});
});
Works :-)
Since this is a menu, might as well take it to the next level, and clean up the HTML, and make it more semantic by using a list element:
HTML:
<ul id="menu">
<li>Bla</li>
<li>Bla</li>
<li>Bla</li>
</ul>
CSS:
#menu {
margin: 0;
}
#menu li {
float: left;
list-style: none;
margin: 0;
}
#menu li a {
display: block;
line-height:30px;
width:100px;
background-color:#000;
}
#menu li a:hover {
background-color:#F00;
}
On a side note this is more efficient:
$(".menuItem").hover(function(){
this.style.backgroundColor = "#F00";
}, function() {
this.style.backgroundColor = "#000";
});
I prefer foxy's answer because we should never use javascript when existing css properties are made for the job.
Don't forget to add display: block ; in .menuItem, so height and width are taken into account.
edit : for better script/look&feel decoupling, if you ever need to change style through jQuery I'd define an additional css class and use $(...).addClass("myclass") and $(...).removeClass("myclass")
If someone reads the original question to mean that they want to dynamically change the hover css and not just change the base css rule for the element, I've found this to work:
I have a dynamically loaded page that requires me to find out how high the container becomes after data is loaded. Once loaded, I want to change the hover effect of the css so that an element covers the resulting container. I need to change the css .daymark:hover rule to have a new height. This is how...
function changeAttr(attrName,changeThis,toThis){
var mysheet=document.styleSheets[1], targetrule;
var myrules=mysheet.cssRules? mysheet.cssRules: mysheet.rules;
for (i=0; i<myrules.length; i++){
if(myrules[i].selectorText.toLowerCase()==".daymark:hover"){ //find "a:hover" rule
targetrule=myrules[i];
break;
}
}
switch(changeThis)
{
case "height":
targetrule.style.height=toThis+"px";
break;
case "width":
targetrule.style.width=toThis+"px";
break;
}
}
I just coded up an example in jQuery on how to create div overlays over radio buttons to create a compact, interactive but simple color selector plug-in for jQuery
http://blarnee.com/wp/jquery-colour-selector-plug-in-with-support-for-graceful-degradation/
Always keep things easy and simple by creating a class
.bcolor{ background:#F00; }
THEN USE THE addClass() & removeClass() to finish it up

Categories

Resources