Wrong function called after class toggle - javascript

I'm facing such problem. I have div with class oldClass and function that toggle div's class on click. When the class changed clicking on div should trigger other function and call alert, however this behavior doesn't appear and it seems like previous function is called again. I'm quite new in jQuery, so what am I missing?
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$('.oldClass').on('click',function(){
$(this).toggleClass('oldClass').toggleClass('newClass');
});
});
$(function(){
$('.test').on('click',function(){
alert('1111');
});
});
</script>
<style>
.oldClass {
border: 1px solid red;
}
.newClass {
border: 3px solid green;
}
</style>
</head>
<body>
<div class="oldClass" title="qwerty">qwerty
</div>
<body>
</html>

Here you go! You have to subscribe and unsubscribe to events. I'm new to jQuery as well and it might be not the clearest solution, but it works. If anyone can suggest a better solution, you are welcome.
var subNewClass = function () {
$('.newClass').off().on('click', function () {
alert('1111');
});
};
var subOldClass = function () {
};
$(function () {
$('.oldClass').off().on('click', function () {
$(this).toggleClass('oldClass').toggleClass('newClass');
$('.newClass').off().on('click', func);
});
});
.oldClass {
border: 1px solid red;
}
.newClass {
border: 3px solid green;
}
<div class="oldClass" title="qwerty">qwerty</div>

You're declaring document.ready twice ... $(function(){}); is a shortand for $(document).ready(); and not a javascript function declaration ...
To create a function you should first do function foo(){ /* content goes here */ }; or var foo = function(){ /* content goes here */ }; ant then call it whenever you want by writing foo();
Read more about JS functions here
Check this to see how this should work: JSFIDDLE DEMO
var alertTrigger = function (){
$('.newClass').on('click',function(){
$(this).toggleClass('oldClass').toggleClass('newClass');
alert('1111');
});
}
$(function(){
$('.oldClass').on('click',function(){
$(this).toggleClass('oldClass').toggleClass('newClass');
alertTrigger();
});
});

Related

How to open 1 div on mouse hover of second div?

Hi I am trying to open one div on mouse hover of second div.
The div 1 is display is none by default but when user hover on div 2 the div 1 will be displayed.
But it's not working.
My code :
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<style>
.testtmpblock{
display: none;
background-color: black;
height: 100px;
width: 100px;
}
.tmpd{
height: 100px;
width: 100px;
background-color: blue;
}
</style>
<script>
$(document).ready(function () {
$(document).on('mouseenter', '.tmpd', function () {
$(this).find(".testtmpblock").show();
}).on('mouseleave', '.tmpd', function () {
$(this).find(".testtmpblock").hide();
});
});
</script>
</head>
<body>
<div class="tmpd">
kjkjkj
</div>
<div class="testtmpblock">
data
</div>
</body>
</html>
div testtmpblock will be appear on hover of div tmpd but it's not working.
I have also write Script for it.
Any guidance that where I am wrong ?
You need to use next instead of find as find is used for desendants and your required element is not descendant.
Live Demo
$(document).ready(function () {
$(document).on('mouseenter', '.tmpd', function () {
$(this).next(".testtmpblock").show();
}).on('mouseleave', '.tmpd', function () {
$(this).next(".testtmpblock").hide();
});
});
You can avoid next if only single element has class testtmpblock
$(document).ready(function () {
$(document).on('mouseenter', '.tmpd', function () {
$(".testtmpblock").show();
}).on('mouseleave', '.tmpd', function () {
$(".testtmpblock").hide();
});
});
If the divs are next to each other you do this with CSS only:
.testtmpblock {
display: none;
}
.tmpd:hover ~ .testtmpblock {
display: block;
}
If you want to animate it you can use CSS3 transitions.
99% of time you can get away with CSS only, and the animations will be faster with transitions. It's all about how you handle the markup. If you make the hidden element a child then it's always doable with just CSS, for example:
<div class="tmpd">
kjkjkj
<div class="testtmpblock">
data
</div>
</div>
And you'd use a selector like so:
.tmpd:hover .testtmpblock {}
try next()
$(document).on('mouseenter', '.tmpd', function () {
$(this).next(".testtmpblock").show();
}).on('mouseleave', '.tmpd', function () {
$(this).next(".testtmpblock").hide();
});
$(document).ready(function () {
$('body').on('hover','.tmpd', function () {
$(".testtmpblock").show();
}, function () {
$(".testtmpblock").hide();
}
);
});

error in javascript toggle class

I have this code for toggling class using pure JavaScript that I found online and it is not working when I am using it in an offline website
my code is -
<!DOCTYPE html>
<html>
<head>
<script>
function classToggle() {
this.classList.toggle('class1');
this.classList.toggle('class2');
}
document.querySelector('#div').addEventListener('click', classToggle);
</script>
<style type="text/css">
.class1 {
color: #f00;
}
.class2 {
color: #00f;
}
</style>
</head>
<body>
<div id="div" class="class1">click here</div>
</body>
</html>
any help would be appreciated
Move the script below the div you are looking for in the source code.
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.class1 {
color: #f00;
}
.class2 {
color: #00f;
}
</style>
</head>
<body>
<div id="div" class="class1">click here</div>
<script>
function classToggle() {
this.classList.toggle('class1');
this.classList.toggle('class2');
}
document.querySelector('#div').addEventListener('click', classToggle);
</script>
</body>
</html>
You cannot manipulate the dom before it is ready.
So either load the script that adds the handler at the end of the body tag, or use the DOMContentLoaded event.
document.addEventListener("DOMContentLoaded", function(event) {
console.log("DOM fully loaded and parsed");
});
Try adding the event handler after the div has rendered - for example in the onload event
Live Demo
<!DOCTYPE html>
<html>
<head>
<script>
function classToggle() {
if (!this.classList) return; // no support
this.classList.toggle('class1');
this.classList.toggle('class2');
}
window.onload=function() {
document.getElementById('div').onclick=classToggle;
}
</script>
<style type="text/css">
.class1 {
color: #f00;
}
.class2 {
color: #00f;
}
</style>
</head>
<body>
<div id="div" class="class1">click here</div>
</body>
</html>
codepen demo
//vanilla js -- toggle active class
// el = object containing the elements to toggle active class and the parent element
var el = {
one: document.getElementById('one'),
two: document.getElementById('two'),
three: document.getElementById('three'),
hold: document.getElementById('hold')
};
// func = object containing the logic
var func = {
toggleActive: function(ele) {
ele = event.target;
var hold = el.hold.children;
var huh = el.hold.children.length;
var hasActive = ele.classList.contains('active');
for (i = 0; i < huh; i++) {
if (hold[i].classList.contains('active')) {
hold[i].classList.remove('active');
}
}
if (!hasActive) {
ele.classList.add('active');
}
}
};
//add listeners when the window loads
window.onload = function() {
var holdLen = el.hold.children.length;
for (i = 0; i < holdLen; i++) {
el.hold.children[i].addEventListener("click", func.toggleActive);
}
};

jQuery: Highlight div box onload

This jQuery code will highlight the div box when clicked.
I want to get the highlight on load, how can I do that?
<!DOCTYPE html>
<html>
<head>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<style type="text/css">
div { margin: 0px; width: 100px; height: 80px; background: #666; border: 1px solid black; position: relative; }
</style>
<script>
$(document).ready(function() {
$("#div1").click(function () {
$(this).effect("highlight", {}, 3000);
});
});
</script>
</head>
<body">
<div id="div1"></div>
</body>
</html>
Put the statement for highlight in document.ready at the same level you are binding click event..
Live Demo
$(document).ready(function() {
$("#div1").effect("highlight", {}, 3000); //this will highlight on load
$("#div1").click(function () {
$(this).effect("highlight", {}, 3000);
});
});
Alternatively, this way might be a little cleaner in that if you add some other effects that you want to show on the click state, you only need to define them one time.
$(document).ready(function() {
$("#div1").click(function () {
$(this).effect("highlight", {}, 3000);
});
$('#div1').click();
});
Javascript
$(document).ready(function() {
$("#div1").effect("highlight", {}, 3000);
});
This will highlight the div1 when the document is ready. If you also want a click handler, you can keep it and put in whatever code you want (ie. you can also keep the effect in there as well, if you want to).
Fiddle

Can I have a click and keyboard handler for RaphaelJS' canvas events?

I am new to RaphaelJS. I am trying to add click listener and keyboard listener to the canvas with no success. Can someone please explain how to use click listener and keyboard listener on Raphael. A small example will be of great help.
Thank you.
Here is a click and mouseover example, you can use more jQuery in there to simplify it but I just wanted to use the document ready function. Shouldn't be too much to add a keyboard event in there:
<html>
<head>
<script type="text/javascript" src="http://github.com/DmitryBaranovskiy/raphael/blob/master/raphael-min.js?raw=true"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
var paper = new Raphael(document.getElementById('canvas_container'), 500, 500);
var circ = paper.circle(250, 250, 40);
circ.node.onmouseover = function()
{
this.style.cursor = 'pointer';
};
circ.node.onclick = function()
{
circ.animate({opacity: 0}, 2000, function()
{
this.remove();
});
}
});
</script>
<style type="text/css">
#canvas_container
{
width: 500px;
border: 1px solid #aaa;
}
</style>
</head>
<body>
<div id="canvas_container"></div>
</body>
</html>

jQuery UI Sortable -- How can I cancel the click event on an item that's dragged/sorted?

I have a jQuery UI Sortable list. The sortable items also have a click event attached. Is there a way to prevent the click event from firing after I drag an item?
$().ready( function () {
$('#my_sortable').sortable({
update: function() { console.log('update') },
delay: 30
});
$('#my_sortable li').click(function () {
console.log('click');
});
});
#my_sortable li {
border: 1px solid black;
display: block;
width: 100px;
height: 100px;
background-color: gray;
}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/jquery-ui.min.js"></script>
<ul id="my_sortable">
<li id="item_1">A</li>
<li id="item_2">B</li>
<li id="item_3">C</li>
</ul>
I had the same problem and since my sortable items contained three or four clickable items (and the number was variable) binding/unbinding them on the fly didn't really seem an option. However, by incident I specified the
helper : 'clone'
option, which behaved identically to the original sortable in terms of interface but apparently does not fire click events on the dragged item and thus solves the problem. It's as much a hack as anything else, but at least it's short and easy..
If you have a reference to the click event for your li, you can unbind it in the sortable update method then use Event/one to rebind it. The event propagation can be stopped before you rebind, preventing your original click handler from firing.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/jquery-ui.min.js"></script>
<script type="text/javascript" charset="utf-8">
var myClick = function () {
console.log('click');
};
$().ready( function () {
$('#my_sortable').sortable({
update: function(event, ui) {
ui.item.unbind("click");
ui.item.one("click", function (event) {
console.log("one-time-click");
event.stopImmediatePropagation();
$(this).click(myClick);
});
console.log('update') },
delay: 30
});
$('#my_sortable li').click(myClick);
});
</script>
<style type="text/css" media="screen">
#my_sortable li {
border: 1px solid black;
display: block;
width: 100px;
height: 100px;
background-color: gray;
}
</style>
</head>
<body>
<ul id="my_sortable">
<li id="item_1">A</li>
<li id="item_2">B</li>
<li id="item_3">C</li>
</ul>
</body>
</html>
If you for some reason don't want to use the helper:'clone' trick, this worked for me. It cancels the click event on an item that is dragged. jQuery adds the class ui-sortable-helper to the dragged element.
$('.draggable').click(clickCancelonDrop);
function clickCancelonDrop(event) {
var cls = $(this).attr('class');
if (cls.match('ui-sortable-helper'))
return event.stopImmediatePropagation() || false;
}
$('.selector').draggable({
stop: function(event, ui) {
// event.toElement is the element that was responsible
// for triggering this event. The handle, in case of a draggable.
$( event.toElement ).one('click', function(e){ e.stopImmediatePropagation(); } );
}
});
This works because "one-listeners" are fired before "normal" listeners. So if a one-listener stops propagation, it will never reach your previously set listeners.
We can also use a flag on the stop event that and check that flag on the click event.
var isSortableCalled = false;
$('#my_sortable').sortable({
stop: function(event, ui){
isSortableCalled = true;
},
update: function() { console.log('update') },
delay: 30
});
$('#my_sortable li').click(function () {
if(!isSortableCalled){
console.log('click');
}
isSortableCalled = false;
});
The answer by mercilor worked for me a couple of caveats. The click event was actually on the handle element rather than the sorted item itself. Unfortunately the ui object, doesn't give you a reference to the handle in the update event (feature request to jquery ui?). So I had to get the handle myself. Also, I had to call preventDefault as well to stop the click action.
update: function(ev, ui) {
var handle = $(ui.item).find('h3');
handle.unbind("click");
handle.one("click", function (event) {
event.stopImmediatePropagation();
event.preventDefault();
$(this).click(clickHandler);
});
// other update code ...
Easier, use a var to know when the element is being sorted...
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/jquery-ui.min.js"></script>
<script type="text/javascript" charset="utf-8">
$().ready( function () {
$('#my_sortable').sortable({
start: function() {
sorting = true;
},
update: function() {
console.log('update');
sorting = false;
},
delay: 30
});
$('#my_sortable li').click(function () {
if (typeof(sorting) == "undefined" || !sorting) {
console.log('click');
}
});
});
</script>
<style type="text/css" media="screen">
#my_sortable li {
border: 1px solid black;
display: block;
width: 100px;
height: 100px;
background-color: gray;
}
</style>
</head>
<body>
<ul id="my_sortable">
<li id="item_1">A</li>
<li id="item_2">B</li>
<li id="item_3">C</li>
</ul>
</body>
</html>
Thanks to Elte Hupkus;
helper: 'clone'
I have implemented the same and a sample is shown below.
$(document).ready(function() {
$("#MenuListStyle").sortable({
helper:'clone',
revert:true
}).disableSelection();
});
One solution is to use live() instead of normal binding, but Elte Hupkes solution rocks!!!!
$('.menu_group tbody a').click(function(){
link = $(this).attr('href');
window.location.href = link;
});
This solution seems to be working for me. Now i can click on clickables inside sortable elements.
Note: ".menu_group tbody" is .sortable();

Categories

Resources