jQuery addClass function issues - javascript

i have one simple jQuery function, that does not work. I need to write a function that if anyone click on some class called 'modal-opened' it need to add class to body 'modal-open'. So i write function like this:
$(document).ready(function(){
$(".modal-opened").click(function(){
$("body").addClass("modal-open");
});
});
I have that same function in JavaScript that works actually, here it is.
document.getElementById("modal-opened").addEventListener("click", myFunction);
function myFunction() {
$("body").addClass("modal-open");
}
I need that same but in jQuery.

Notice you get modal-opened by ID in plain JS:
// You get modal-opened by ID in plain JS
$(document).ready(function(){
$("#modal-opened").click(function(){
$("body").addClass("modal-open");
});
});

try to do this:
<script>
$(document).on('click','.modal-opened',function(){
$("body").addClass("modal-open");
});
</script>

There is an error in your jQuery code with reference to working javascript code you shared.
document.getElementById("modal-opened") in javascript is equivalent to $("#modal-opened") and not $(".modal-opened").
In jQuery, you can access an element by Id using # and by class using dot.
Hope this helps..
Please share your feedback.

Related

Css onclick change class

I want to change a class when I click.
The class is icon icon_plus, and when i click i want that class to be icon icon_minus-06and if click again back tothe original
My HTML code
<i id="icon" class="icon icon_plus"></i>
My javascript code :
<script>
$("a.top-bar-trigger").click(ontop);
function ontop() {
$("#icon").toggleClass("icon icon_minus-06");
}
</script>
I am very weak with javascript
Thanks for the help.
Try to write toggleClass like this,
$("#icon").toggleClass("icon_plus icon_minus-06");
Since you are keeping icon class as a static one.
DEMO
Also as a side note, try to wrap your code inside document's ready handler. Since the selector would fail, if you keep your script inside header tag. But If you have placed your script in the end of body tag, then no issues. Anyway its better to use document's ready handler as it would make the code more procedural.
The code should be like this,
(function(){
function ontop() {
$("#icon").toggleClass("icon_plus icon_minus-06");
}
$(function(){
$("a.top-bar-trigger").click(ontop);
});
})();
You can solve this problem in two ways.
1) Using AddClass & RemoveClass Methods
$("a.top-bar-trigger").click(changeClass);
function changeClass() {
if($("#icon").hasClass('icon_plus')){
$("#icon").removeClass("icon_plus").addClass("icon_minus-06");
}
else{
$("#icon").removeClass("icon_minus-06").addClass("icon_plus");
}
}
2) Using ToggleClass
$("a.top-bar-trigger").click(changeClass);
function changeClass() {
$("#icon").toggleClass("icon_plus icon_minus-06");
}
You can check the JSFiddle Links here
1) https://jsfiddle.net/4vzsn4kt/
2) https://jsfiddle.net/zzq820eu/
You can try this way:
$("a.top-bar-trigger").click(function(){
$(".icon").toggleClass("icon_minus-06");
});
Fiddle: https://jsfiddle.net/5au3ywmz/2/
PROBLEM SOLVED
The code you have works if its run after the DOM is ready, you can see it working here: jsfiddle.net/hosw2wc9 – Adam Konieska

document.getElementById() alternative in jQuery

UPDATE: I'm sorry that my thread was misinterpreted by many users. I'll try to be more clear.
I'm using Drupal and I have created three floating banners. On the frontpage there is a block (block1) that displays one floating banner and after refresh the second one is appearing and for the third too.
Like a wrote before these banners has a little X button to stop overflow.
I've putted this script in a one of the banners and it's working great.
<script language="javascript">
function doexpand() {
document.getElementById("block1").style.overflow = "visible";
}
function dolittle() {
document.getElementById("block1").style.overflow = "hidden";
}
</script>
The real problem is that in categories pages I have #block2 and in articles #block3.
These block are displaying the same banners. The code over is working only for a one ID. In this case #block1. document.getElementById is not working for more ID's as I read from other topics.
I've tried with jQuery with two blocks idents like this:
(function ($) {
function doexpand() {
$("#block1,#block2").css("overflow","visible");
}
function dolittle() {
$("#block1,#block2").css("overflow","hidden");
}
})(jQuery);
It's not working.
The firebug/console displays: ReferenceError: doexpand is not defined.
I've tried with a single block too with jQuery like this:
(function ($) {
function doexpand() {
$("#block1").css("overflow","visible");
}
function dolittle() {
$("#block1").css("overflow","hidden");
}
})(jQuery);
and it's displaying the same error.
Note: Drupal has a different wrapping and it's like this:
(function ($) {
//your existing code
})(jQuery);
Please have a look on jQuery Selectors.
I think in your case, it is better to apply style with help of css for multiple elements. e.g. :
<script language="javascript">
function doexpand() {
$('.block').style.overflow="visible";
}
function dolittle() {
$('.block').style.overflow="hidden" ;
}
</script>
Please add class="block" to all of blocks for which you want to apply this style/function, it will apply on all of the blocks having css class "block".
jQuery?
HTML:
<div class="block2"></div>
JS:
function doExpand(selector) {
if ( $(selector).length ) {
$(selector).css({'overflow':'visible'});
}
}
Calling with non ID selector would look like this: (jQuery syntax):
doExpand('.block2');
The above code is perfectly valid in jQuery (which is a JavaScript library).
If you want to use a more typical jQuery code, you can do
$('#block1').css('overflow', 'visible');
You can expend it to multiple id like this :
$('#block1, #block2').css('overflow', 'visible');
You always can get the DOM object from a jQuery object, which means you could also have adapted your code to use jQuery selectors using
$('#block1').get(0).style.overflow="visible";
(this specific example isn't smart : no need to use jQuery if you don't use a complex selector or jQuery functions)
Pretty simple really, jQuery selection is based on css selectors for the most part. These selectors are then translated into an array of dom objects held in a jQuery object.
function doexpand() {
$("#block1").css("overflow","visible");
}
function dolittle() {
$("#block1").css("overflow","hidden");
}
You should never have more than one HTML element with the same ID (Which is why document.getElementById only returns one element)
You can just refeerence block2, block3 directly document.getElementById("block2").style.overflow="hidden" ;
Or use getElementByClassName
var elements = document.getElementsByClassName("yourClass")
Which will pick up all elements with a specific class.
If you want to use jQuery like the other answers are suggesting you can match on the element name. For example:
$('div[id^="block"]').css("overflow", "visible");
This will match all div element where their ID starts with block. You can also use other wildcards such as * for contains and $ for ends with.
Here is your Javascript Code in jQuery. I dont understand what you want do do, but you could pass the params in the function. Example under this code.
<script language="javascript">
function doexpand() {
$("#block1").css({'overflow': 'visible'});
}
function dolittle() {
$("#block1").css({'overflow': 'hidden'});
}
</script>
Here is it
<script language="javascript">
function doexpand(element) {
$("#" + element).css({'overflow': 'visible'});
}
function dolittle(element) {
$("#" + element).css({'overflow': 'hidden'});
}
</script>
Than you could call it like: doexpand("theIDofTheElement");
Alternative to document.getElementById("an_element);
in Jquery is: $("#an_element");
It will work fine in JQuery, it's just that JQuery makes things faster and less verbose.

How do you put a jquery function inside a javascript function?

I am validating my form using Javascript, but would like to display the errors using Jquery. Can you do this?
you can do this:
function Validate(){
if(isValidate){
// do somthing
}else{
$("#error").fadeIn(500);// here is jQuery code
}
}

Writing javascript with jquery and using a variable

As a javascript newbie, I am struggling to use a script with a variable that runs a bit of JQuery (and also struggling to use the right language here, I'm sure!)
The action I want to happen is to change the CSS class of a specific div, e.g. #det90, for which I have the following code (I have used the same on a $(window).load(function() and it works on a different set of divs):
$("#MYDIVIDHERE").switchClass("sdeth","sdet",50);
So I wrote the following:
<script type="text/javascript">
$(function revealCode(divID) {
$("#divID").switchClass("sdeth","sdet",50);
})
</script>
and called it from an anchor with:
onClick="revealCode('det90');"
I think the problem is that I don't know how to write the script and pass the variable in the brackets (divID) to the next line (where I've got "#divID"). Any help or pointers to tutorials gratefully received!
Solution
Thanks to all, but particularly to Caleb. I've scrapped the general function and the onClick, added an ID to the anchor and inserted the following for that anchor (and then repeated that for each anchor/div combination I want to use it on ... and it works :D
$("#linkID").click(function() {
$("#divID").switchClass("sdeth","sdet",50);
});
Change your code to: onClick="revealCode('#det90');"
$(function revealCode(selector) {
$(selector).switchClass("sdeth","sdet",50);
})
jQuery is powered by "selectors" -- similar to CSS syntax.
Don't quote your variable name. Just quote the "#" prefix.
<script type="text/javascript">
$(function revealCode(divID) {
$("#" + divID).switchClass("sdeth","sdet",50);
})
</script>
Change to:
<script type="text/javascript">
function revealCode(divID) {
$("#" + divID).switchClass("sdeth","sdet",50);
}
</script>
You don't need $() around the function
$("#divID") will look for an element with the ID divID, and not what was specified in your function parameter
This won't work. revealCode is local to that scope and not known outside. Also, you're not using the argument you've passed into your handler.
If you're using jQuery, use it to bind to the handler as well like this:
jQuery(document).ready(function() {
function revealCode(divID) {
$("#" + divID).switchClass("sdeth","sdet",50);
}
jQuery("#divID").click(function() {
revealCode('det90');
});
});
Move your onclick event handler attachment into javascript code. You should try not to mix your functional code with your html.
Anonymous version:
$('#myDiv').click(function () {
$(this).switchClass("sdeth","sdet",50);
});
Normal version:
var myFunction = function (element) {
$(element).switchClass("sdeth","sdet",50);
};
$('#myDiv').click(myFunction, {element: this});

Dropdownlist change event not working in IE9

I have this piece of code, that just refuses to co-operate, I've tried to look over the syntax, tried .change, .click events, nothing works, I am trying to alert the user, if the function works, nothing.
Heres the Javascript code:
$('#ProductNamesList').change(function () {
alert('JQuery works!');
});
And the HTMLHelper that generates the drop down list
#Html.DropDownList("ProductNamesList", New SelectList(Model.ProductList))
Can someone please help? I can't test it in other browsers, due to our requirements here -.-
For the record, I am using jquery-1.6.4.js and jquery-ui-1.8.16.js
Try this
$(document).ready(function() {
$('#ProductNamesList').live('change', function (event) {
alert('JQuery works!');
});
});
Looking at your live demo, it seems the problem is with the use of name="#sel". The correct notation is id="sel".
If you insist on use of name attribute, use jQuery selector [name="sel"]. Also note that the hash sign is redundant in attribute value.
I don't see anything wrong with it, the following worked for me in Firefox and IE8 (don't have IE9 available here).
#Html.DropDownList("ProductNamesList", new SelectList(Model.ProductList))
<script type="text/javascript">
$('#ProductNamesList').change(function () {
alert('JQuery works!');
});
</script>
Is the masterpage hooked up properly, and the reference to jquery correct?
I have tried the following code and it works.
<form action="">
<select id="sel">
<option>AUDI</option>
<option>Axel</option>
<option>BCS</option>
<option>BIBO</option>
</select>
</form>
<p id=result>
And the javascript:
$(document).ready(function() {
$("#sel").change(function () {
alert("JQuery works!");
});
});
When I try it at your live demo, I am getting error $ is not defined. I have created a jsfiddle which also works fine.
http://jsfiddle.net/rtFUs/
So all you have to do is to make sure that you are adding jquery correctly and the id of the select box is "mySelectBoxId" and you reference it using #, for example $("#mySelectBoxId"), that's it.

Categories

Resources