Checking visibility with jQuery (debug) - javascript

I followed a few posts to be able to check the visibility of a div :
HTML :
<div class="language" onclick="Show_Div()">
<div class="menu-langues">
//my code here
</div>
</div>
Script :
function Show_Div() {
$Div_id = "menu-langues";
if ( $(Div_id).is(':hidden')) {
($Div_id).show();
}
else {
($Div_id).hide();
}
}
Console :
Uncaught ReferenceError: Div_id is not defined
I can't see what i did wrong, can someone help me with this?
Thank's ! :)

You've defined a variable, then used a different one in your code in the if-statement.
if ( $(Div_id).is(':hidden')) {
should be
if ( $($Div_id).is(':hidden')) {
That should solve the error. However, to get working code I'd recommend writing like this:
function Show_Div() {
$Div_id = $(".menu-langues");
if ( $Div_id.is(':hidden')) {
$Div_id.show();
}
else {
$Div_id.hide();
}
}
This way you're turning the variable $Div_id into a jQuery object, on which you can execute functions. By saving it in the variable, the code doesn't have to look for the element over and over again.

Don't mix inline event handlers like onclick with jQuery. jQuery handlers will do a better job and have extra features. And, as #Rory McCrossan said, just use toggle.
Code:
$('.language').click(function(){
// Show if hidden and hide if visible
$('.menu-langues').toggle();
});
Html (no inline handler):
<div class="language">
<div class="menu-langues">
//my code here
</div>
</div>
If you had multiples of the same button on the page, you can target the selection using a scoped selector (second parameter defines the scope):
$('.language').click(function(){
// Show if hidden and hide if visible
$('.menu-langues', this).toggle();
});

Some errors: menu-langues is a class not an ID, so, you can reference this with jQuery as: $('.menu-langues')
If you need reference to an ID, use jQuery: $('#menu-langues')
So, use '.' to reference a class and '#' to reference an ID.
You used $Div_id = "menu-langues"; ...and I changed it to: Div_id = "menu-langues";
And too you write $(Div_id).show(); and I fixed to: $(Div_id).show();
The snipped code fixed and working:
function Show_Div() {
var Div_id = ".menu-langues"; // is a class, not ID
if ( $(Div_id).is(':hidden')) {
$(Div_id).show();
}
else {
$(Div_id).hide();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="language" onclick="Show_Div()">
<div class="menu-langues">
test of visibility
</div>
</div>
<button onClick="javascript:Show_Div();">Click</button>

Your variable name is $Div_id not Div_id. Also you are trying to select with class name so you would need to prepend a . to your selector.
Your code should look like:
function Show_Div() {
$Div_id = ".menu-langues";
if ( $($Div_id).is(':hidden')) {
$($Div_id).show();
}
else {
$($Div_id).hide();
}
}

The code should be more like:
function Show_Div() {
var $Div_id = "menu-langues";
if ( $($Div_id).is(':hidden')) {
$($Div_id).show();
} else {
$($Div_id).hide();
}
}
It's also worth mentioning that the convention for JavaScript variable names and function names is camelCase.

Related

How to use THIS in child function which is outside of a parent JS

I have an onclick function
$('.modal-trigger').on('click', function() {
$('#'+$(this).data('modal')).show();
calc();
})
<a class="modal-trigger" data-modal="ft-modal">Link</a>
<div id="ft-modal"></div>
I want to add calc() function inside
function calc() {
var tt = document.getElementById('#'+this.getAttribute('data-modal')).document.getElementsByClassName("name-line")[0];
}
The second function is outside (above) the onclick one, and my problem is that I can't figure it out how to perform a search inside the <div> by class name and get the first one that matches the class on plain JS.
And I think that I don't know how to use this properly for this particular case.
You can pass this to the calc function with .call:
calc.call(this);
The calc function needs no change then.
You have to pass this object to the function so that you can refer that inside the function. You can simplify your code by using jQuery:
$('.modal-trigger').on('click', function() {
$('#'+$(this).data('modal')).show();
calc(this); // pass this here
})
function calc(el) {
var tt = $('#'+$(el).data('modal')).find('.name-line')[0];
console.log(tt);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a class="modal-trigger" data-modal="ft-modal">Link</a>
<div id="ft-modal">
<span class="name-line"></span>
</div>
as suggested in the comments...
$('.modal-trigger').on('click', function() {
...
calc(this);
});
function calc(ele) {
...
}
using document.getElementById in a jQuery script is questionable;
better use $(ele).data('modal') to obtain the data attribute.
of couse both ways would work, nevertheless the readability would be improved
... that's why it is called "write less, do more".

How to check if a HTML element contains an other one?

I want to check if my title <h3> has the class highlight so I founded How to check if element contains specific class attribute but I'm not sure about how to fit it to my use case because it's not the <h3> which contains the class but the span inside it:
I tried to do this code:
$('.liContainer div h3').each(function(i, obj) {
var contains = false;
String classes = obj.getAttribute("class");
for (String c : classes.split(" ")) {
if (c.equals("highlight")) {
contains = true;
}
}
if(contains){
obj.classList.remove("highlight");
}
});
but I got an error with the actual code:
imports/ui/layout.js:42:13: Unexpected token (42:13)
and it's the line String classes = obj.getAttribute("class");
Could someone help me to make it works ?
[EDIT] with the help of your answer I'm now here:
'click .liContainer div h3': function(e){
if ( $(e.target).find("span").is(".highlight") ) {
console.log("it was highlighted");
$(e.target).find("span").removeClass('highlight');
}
},
and it works so thank you everybody
I hope it will help you
$('.liContainer div h3').each(function(i, obj) {
if ( $(this).find("span").is(".highlight") ) {
// do something
}
});
**can you just help me to do the action only on the clicked h3?**
If `click` action:
$('.liContainer div h3').click(function() {
if ( $(this).find("span").is(".highlight") ) {
// do something
}
});
I use your code, and change the content of the `each` loop.
You loop each `<h3>` and check if child `<span>` has class `.highlight`, then you do something...
The above Code can also be written as follows:
$('.liContainer div h3').click(function() {
if ( $(this).find("span.highlight") ) {
// do something
}
});
Hope this works fine.
$('h3').filter(function(){
return $(this).find('span.highlight').length != 0;
}) // do something with it
A rough way to know if you don't know have child selector
$('#nameMachine *').hasClass('yourClass'); // either true or false
Since you are using jquery, how about this simple solution:
$('.liContainer div h3 .highlight').removeClass('highlight');
Try using `has` selector as given below code :
$('.liContainer div h3:has(span.highlight)').each(function(){
// code here
});
You may try something like:
if( $("h3", "#nameMachine").has(".highlight") ) {
// do something
}
Or a more specific version:
if( $("> h3", "#nameMachine").has("span.highlight") ) {
// do something
}
$('span.highlight','.liContainer div h3').removeClass('highlight')
Please note that the second css selector is to determine the scope of searching the first css selector.
find() will be searching in all of child element . So if there have wanted class its length will be 1 else length is 0.
$('.liContainer div h3').each(function(i, obj) {
var hasClass = $(obj).find(".highlight");
if (hasClass.length) {
hasClass[0].classList.remove("highlight");
}
});
This will do. hasClass documentation is here
$("#nameMachine h3").hasClass("highlight")
if ($('#parent').find('#child').length) {
}

Jquery/Javascript Add class if X class is not exist

I am new here, sorry if I do some mistake with this question.
I have a HTML code.
hit me
with this function i can add class two in class one
$(document).ready(function () {
$('a#foo').click(function(){
$('.one').toggleClass('two');
});
});
but how if I want to add class two if class two is not exist and do other function if class two is exist?
maybe like this,
hit me
i klik hit me and jquery is add class two,
hit me
but when I klick hit me again, class two is not removed and because class is exist, i create other function based on class two is exist.
lets say like this,
i klik hit me
hit me
<div id="blah" class=""*>lorem</div>
then
hit me
<div id="blah" class=""*>lorem</div>
and klik hit me again.
hit me
<div id="foo" class="blah2">lorem</div>
can you give me code or google suggest keyword or link, because I confused what i must search first.
thanks for adv,
sorry for my Grammer, i cant speak/write English well, if any wrong grammer or language please correct me.
Using the hasClass() method and you're examples:
$(document).ready(function () {
$('a#foo').click(function(){
if ($(this).hasClass('two')) {
$('#blah').addClass('blah2');
} else {
$(this).addClass('two');
}
});
});
Use jQuery hasClass method .
$(document).ready(function () {
$('a#foo').click(function(){
if ($(this).hasClass('two')) {
doSomething();
} else {
$('.one').addClass('two');
}
});
});
i'm a little confused as to what exactly you want to do, but I think you need to look into .hasClass() for starters.
$(document).ready(function () {
$('a#foo').click(function(){
if ($('.one').hasClass('two')) {
// do stuff you want to do if element already has class "two"
}
else {
// do stuff if it doesnt already have class "two"
}
});
});
I am guessing at your exact needs, but I hope that my assumptions weren't too far off base.
Given HTML like this:
hit me
<div id="change" class="blah1"></div>
And JS Like this:
$(document).ready(function () {
$('a#foo').click(function(e){
e.preventDefault();
var changeDiv = $('#change');
if ($(this).hasClass('two')) {
changeDiv.addClass('blah2').removeClass('blah1');
changeDiv.html('<p>Blah 2</p>');
} else {
changeDiv.addClass('blah1').removeClass('blah2');
changeDiv.html('<p>Blah 1</p>');
}
$('.one').toggleClass('two');
});
});
You will be able to toggle your link's class and change or update another div based on the class of your link when clicked.
You can see this code working at http://jsfiddle.net/PTdLQ/4/
Another way to look at this is to check if the given class exists in the dom. Therefore, one can use the following:
$(document).ready(function () {
$('a#foo').click(function(){
if ($('.two').length) {
//there is a class two
SomeFunction();
} else {
//there is no class two
SomeOtherFunction();
}
});
});
Hope I typed it right
Use this code:
<script>
$(document).ready(function () {
if(!$('#mydiv').hasClass('myclass')) {
$('#mydiv').addClass('myclass');
}
});
</script>

Regular Expression: replace everything but not a specific word

I'm trying to perform a simple replace(); method in JavaScript where I'd like to remove every class from an HTML element except a specific one, how can I do it?
I tried this without success:
<div id="my_div" class="hello letsgo baby is_checked cool">Gordon Freeman</div>
<script>
$(document).ready(function () {
alert ($(#my_div).attr("class").replace (/^(is_checked)$/, ""));
// id'like it returns "is_checked" or "" to work like a boolean;
});
</script>
You're trying to alert is_checked when it's there, right? Try using .hasClass:
$(document).ready(function () {
if($("#my_div").hasClass("is_checked")) {
alert("is_checked");
}
else {
alert("");
}
});
If you just want to know whether an element has a certain class on it, this returns true or false telling you exactly that:
$("#my_div").hasClass("is_checked")
$(document).ready(function () {
if ($(this).hasClass('is_checked') {
$(this).removeClass();
$(this).addClass('is_checked');
}
});
if ($(this).hasClass('is_checked'))
$(this).removeClass().addClass('is_checked');
else
$(this).removeClass();
You want to remove every class except a specific one? You can use jQuery's attr() method and define the class specifically:
$('#my_div').attr('class','is_checked');
Here's an example of this in action: http://jsfiddle.net/decHw/
Also important to note that if you wish to select an element in jQuery by its id, you need to wrap it in quotes. You have:
$(#my_div)
It should be:
$('#my_div')

Passing in parameter from html element with jQuery

I'm working with jQuery for the first time and need some help. I have html that looks like the following:
<div id='comment-8' class='comment'>
<p>Blah blah</p>
<div class='tools'></div>
</div>
<div id='comment-9' class='comment'>
<p>Blah blah something else</p>
<div class='tools'></div>
</div>
I'm trying to use jQuery to add spans to the .tools divs that call variouis functions when clicked. The functions needs to receive the id (either the entire 'comment-8' or just the '8' part) of the parent comment so I can then show a form or other information about the comment.
What I have thus far is:
<script type='text/javascript'>
$(function() {
var actionSpan = $('<span>[Do Something]</span>');
actionSpan.bind('click', doSomething);
$('.tools').append(actionSpan);
});
function doSomething(commentId) { alert(commentId); }
</script>
I'm stuck on how to populate the commentId parameter for doSomething. Perhaps instead of the id, I should be passing in a reference to the span that was clicked. That would probably be fine as well, but I'm unsure of how to accomplish that.
Thanks,
Brian
Event callbacks are called with an event object as the first argument, you can't pass something else in that way. This event object has a target property that references the element it was called for, and the this variable is a reference to the element the event handler was attached to. So you could do the following:
function doSomething(event)
{
var id = $(event.target).parents(".tools").attr("id");
id = substring(id.indexOf("-")+1);
alert(id);
}
...or:
function doSomething(event)
{
var id = $(this).parents(".tools").attr("id");
id = substring(id.indexOf("-")+1);
alert(id);
}
To get from the span up to the surrounding divs, you can use <tt>parent()</tt> (if you know the exact relationship), like this: <tt>$(this).parent().attr('id')</tt>; or if the structure might be more deeply nested, you can use parents() to search up the DOM tree, like this: <tt>$(this).parents('div:eq(0)').attr('id')</tt>.
To keep my answer simple, I left off matching the class <tt>"comment"</tt> but of course you could do that if it helps narrow down the div you are searching for.
You don't have a lot of control over the arguments passed to a bound event handler.
Perhaps try something like this for your definition of doSomething():
function doSomething() {
var commentId = $(this).parent().attr('id');
alert(commentId);
}
It might be easier to loop through the comments, and add the tool thing to each. That way you can give them each their own function. I've got the function returning a function so that when it's called later, it has the correct comment ID available to it.
The other solutions (that navigate back up to find the ID of the parent) will likely be more memory efficient.
<script type='text/javascript'>
$(function() {
$('.comment').each(function(comment) {
$('.tools', comment).append(
$('<span>[Do Something]</span>')
.click(commentTool(comment.id));
);
});
});
function commentTool(commentId) {
return function() {
alert('Do cool stuff to ' + commentId);
}
}
</script>
Getting a little fancy to give you an idea of some of the things you can do:
var tool = $('<span>[Tool]</span>');
var action = function (id) {
return function () {
alert('id');
}
}
$('div.comment').each(function () {
var id = $(this).attr('id');
var child = tool.clone();
child.click(action(id));
$('.tools', this).append(child);
});
The function bind() takes, takes the element as a parameter (in your case the span), so to get the id you want from it you should do some DOM traversal like:
function doSomething(eventObject) {
var elComment = eventObject.parentNode.parentNode; //or something like that,
//didn't test it
var commentId= elComment.getAttribute('commentId')
alert(commentId);
}

Categories

Resources