How to set "style=display:none;" using jQuery's attr method? - javascript

Following is the form with id msform that I want to apply style="display:none" attribute to.
<form id="msform" style="display:none;">
</form>
Also the check should be performed before adding the "style=display:none;" property. That is if it is already set like in above code it should not set again.
But if it's not set then it should.
How should I achieve this? Please help me.

Why not just use $('#msform').hide()? Behind the scene jQuery's hide and show just set display: none or display: block.
hide() will not change the style if already hidden.
based on the comment below, you are removing all style with removeAttr("style"), in which case call hide() immediately after that.
e.g.
$("#msform").removeAttr("style").hide();
The reverse of this is of course show() as in
$("#msform").show();
Or, more interestingly, toggle(), which effective flips between hide() and show() based on the current state.

As an alternative to hide() mentioned in other answers, you can use css() to set the display value explicitly:
$("#msform").css("display","none")

$(document).ready(function(){
var display = $("#msform").css("display");
if(display!="none")
{
$("#msform").attr("style", "display:none");
}
});

You can use the hide and show functions of jquery. Examples
In your case just set $('#msform').hide() or $('#msform').show()

Based on the comment we are removing one property from style attribute.
Here this was not affect, but when more property are used within the style it helpful.
$('#msform').css('display', '')
After this we use
$("#msform").show();

You can just use: $("#msform").hide(). This sets the element to display: none

You can use the jquery attr() method to achieve the setting of teh attribute and the method removeAttr() to delete the attribute for your element msform
As seen in the code
$('#msform').attr('style', 'display:none;');
$('#msform').removeAttr('style');

Please try below code for it :
$('#msform').fadeOut(50);
$('#msform').fadeIn(50);

Related

Convert Javascript code, that changes DOM element's background color, to JQuery

I am new in jQuery and still learning. My problem is I don't know how to convert the following javascript code to jQuery.
Javacript:
document.getElementsByClassName('p-bg')[0].style.backgroundColor = '#'+this.color
Thanks in advance guys.
By the way this is the full code:
<input class="color" onchange="document.getElementsByClassName('p-bg')[0].style.backgroundColor = '#'+this.color">
Thanks again
$(".color") jQuery class selector
.change .change() form events
.eq() .eq() filter elements
.css() .css() manipulation
$(".color").change(function(){
$(".p-bg").eq(0).css("background-color", $(this).css("color"));
})
Note document.getElementsByClassName('p-bg')[0] in jQuery is equivalent to $(".p-bg").eq(0)
Remember that in jQuery, the DOM must be loaded to start working, eg:
$(document).ready(function(){
//You jQuery code here...
})
$('.p-bg:first').css('backgroundColor','"#"+this.color');
The change function binds a function that will execute onchange of the selection set which is in our case all elements with class = 'color'.
$(this) within the function will refer to the current DOM element onchange in the selection, so in this way we catch it's color property.
$('.p-bg:first'), here we are selecting all elements with class p-bg, and to obtain the first element we are using the :first Pseudo Class Selector, then using the css jquery function, we are defining the css property in the first paramerter 'backgroundColor' and the value of the property in the second parameter using another css property (the color) of the current element $(this).css("color").
When we use css function with one parameter it will return the value, with 2 parameter we will be setting the value.
The code below will be the change in jquery.
$(".color").change(function(){
$('.p-bg:first').css('backgroundColor', $(this).css("color"));
});
If you really want to look alike that as you have used Js in your html, this will work for you (Only one line code):
<input class="color" onchange="$(this).css('background-color',$(this).css('color'))">
But i will recommend you to create a change function and then work on it.
Html:
<input class="color">
Script:
<script>
$('.color').on('change',function(){
$(this).css('background-color',$(this).css('color'));
});
</script>
Explanation:
$(this) will get this element for you. then using .css('background-color',$(this).css('color')) will assign its color to its background.

Hide/show element with a boolean

I tend to have a lot of these in my code
if(shouldElementBeVisible)
$element.show()
else
$element.hide()
Is there any more elegant way packaged with javascript, jquery, or underscore? Ideally I want something that looks like this
$element.showOrHideDependingOn(shouldElementBeVisible)
Apparently you can just pass a boolean to the toggle function
$element.toggle(shouldElementBeVisible)
Yes there is!
$element.toggle();
Without any parameters, toggle just toggles the elements visibility (I don't mean the visibility property) and depends on the current state of the element.
$element.toggle(display);
If you call toggle with a boolean parameter, element is shown if it is true and hidden if it is false
source
jQuery has toggle: http://api.jquery.com/toggle/
$element.toggle();
This will show the element if it's hidden, and hide it if it's shown.
$element[ shouldElementBeVisible?'show':'hide' ]()

Hiding button in JQuery using .prop(hidden: true)

I am trying to figure out how to hide a button with JQuery using the .prop(hidden: true) method. For some reason, in Chrome when I set this value and view the html, the button has a hidden element, but the button still shows up as visible on the page.
Any ideas?
A button does'nt have a hidden property ?
$('button').hide();
or
$('button').toggle(true); //shows button
$('button').toggle(false); //hides button
You can use set the display style to none. For example,
$("#button").css("display", "none");
Or, .hide() for brevity,
$("#button").hide()
There's also visibility and opacity but these two may not generate the effect you desired.
You can't hide a button using jQuery's .prop() function, you have to use either .hide() or .fadeOut() or you can try with .css() method:
using .css():
$('input[submit]').css('display','none');
using fadeOut():
$('input[submit]').fadeOut();
using .hide():
$('input[submit]').hide();
Your syntax is incorrect, but there's no "hidden" property anyway. You probably want:
$('#your_button').hide();
or possibly
$('#your_button').addClass('hidden');
if you've got a "hidden" class in your CSS.
The incorrect part of your syntax is that the parameters to your function call are expressed incorrectly. Setting a property should look like:
$("#your_button").prop("name", "value");
jQuery.prop is intended for HTML attributes only, things defined on the DOM node. CSS styles aren't applicable things to set with prop, and hidden just doesn't exist, whereas href or class is applicable. Instead you must use $(el).css('display', 'none') or $(el).hide().
What you described is actually correct if you happen to use jquery alongside bootstrap4.
just do the following:
$element.prop('hidden', true);
If no bootstrap 4 available it is still works for modern browser.
prop() is a getter function: http://api.jquery.com/prop/ I suggest using hide: http://api.jquery.com/hide/
If you want to use prop, then
$("#my_button").prop("style").display="none"
I would go w/o jquery. (back to the basic)
document.getElementById("mybutton").style.display = "none";
You can use a ternary operator and the css() method to accomplish the same thing: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
$("#button").css("display", (mycondition) ? "block" : "none");

How can I set the class for an element using jQuery? Don't want to add/remove classes

I need to set the class for an element in my page. With plain JavaScript, I would write something like:
document.getElementById('foo').className = "my_class";
This just sets the class, which is exactly what I want. But I'm using jQuery on my page and so would like to do this in a "jQuery way", since it seems weird to mix the old style and the jQuery style. But jQuery apparently only allows you use addClass() or removeClass(), like so:
$('#foo').addClass("my_class");
The problem is that it merely adds a class to the element, it does not replace the currently existing class. Does this mean I have to keep track of the old class and do a removeClass() first? Is there no way to tell jQuery to replace the current class no matter what it is and just replace it with a new one?
To remove all classes from an element:
$('#foo').removeClass();
Specifying no arguments to removeClass removes all the classes. So your solution would be:
$('#foo').removeClass().addClass('my_class');
Set the class attribute directly using .attr():
$('#foo').attr('class', 'my_class');
You could use the .attr() function like so:
$('#foo').attr('class', 'my_class');
You could use that:
$('#foo').attr('class', 'my_class');
It will replace any class with "my_class"
$('#foo').removeClass().addClass('my_class');
Ah, found the answer just seconds after I posted the question. Apparently my Google skills were insufficient... :-(
At any rate, the answer is in the removeClass() function. So, you can do:
$('#foo').removeClass().addClass("my_class");
Couldn't be simpler.
you can try using .toggleClass()

jQuery Hide using ID

I'm trying to change the border color of an image using its id with jquery
( photo['id'] is passed in from a previous function )
the ids of the photos are of the form 'photo239839'
$('#photo'+photo['id']+'').click(function(){
$('#photo'+photo['id']+'').css('border-color','#777');
});
When I try to use this same code using its class it works,
but I can't use this method since there are multiple images on the same
page with the same class
$('img.flickr_photo').click(function() {
$("this.flickr_photo").css('border-color','#777');
});
This is what you need to do:
$('img.flickr_photo').click(function(){
$(this).css('border-color','#777');
});
I would always always add a css class rather than an inline style.
Much more maintainable and extensible.
Example:
$('img.flickr_photo').click(function(){
$(this).addClass('greyishBorder');
});
Either photo['id'] is wrong, or is changing after you set up the click handler.
To test for the first case, you can alert (or console.log with FireBug, or whatever) the length of the jQuery selection:
alert($('#photo'+photo['id']).length);
The solution in the second case is to use 'this'. In the click handler, 'this' is set to the element that caused the click event.
$('#photo'+photo['id']).click(function(){
$(this).css('border-color','#777');
});
Edit: #Dreas Grech is right, as long as you want to apply the behavior to all the elements with the flickr_photo class. If you can generalize the selector to select all the elements with a single query, it's better to do that.

Categories