showing/hiding html elements with javascript - javascript

which option among the following is better or used as a standard way to show/hide the html elements
changing element.style.display
adding/removing a separate class called hide {display: none}
any other standard way
PS: this JavaScript hide/show element question uses the first option mentioned( changes the style to block to show which may not be desired). I would like to know whether this method is used in most websites or the adding /removing a separate class or any other way
A third way in the answers below https://stackoverflow.com/a/68983509/14478972

I prefer to toggle a class using DOMTokenList.toggle():
The toggle() method of the DOMTokenList interface removes a given token from the list and returns false. If token doesn't exist it's added and the function returns true.

Well except the first and second, there is the other way.
Which is rendering the element its self.
It has a better security. as the user wont know if there is a hidden element inside the toggle div. Eg when people try to look at the html
Have a look below
I used jQuery as its easier to write. If you are not able to rewrite a JavaScript version will be happy to rewrite for you.
var items = $(".toggle");
var item = {};
// setup the auto toggle
$(".toggle").each(function(el) {
var id = new Date().getUTCMilliseconds() + $(this).index()
item[id] = $(this).find("content")
if (!$(this).hasClass("show")){
$(this).find("content").remove();
}
$(this).attr("id", id)
});
$(".toggle").click(function() {
if ($(this).find("content").length > 0)
$(this).find("content").remove();
else $(this).append(item[$(this).attr("id")])
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="toggle">
<h1>click here to toggle content </h1>
<content>
this is a test
</content>
</div>
<div class="toggle show">
<h1>click here to toggle content(start state is visible) </h1>
<content>
this is a test
</content>
</div>

Option 1 would be standard for only hiding the element, but if you would like to add other styles like transitions and pointer events option 2 is preferred

Related

Show nth:div 1, when i click nth: anchor

Good Evening helpful people of stackoverflow,
I want to hide the **clicked ** .project-tile-normal and show the appropriate description div .detail-tile.
I read through some articles regarding my question, but i run into a logical brickwall in my head. Needlessly to say, i'm a beginner in jquery and maybe there is a better way to do that, i just didn't find it.
Here's what i found so far as "answers":
Hide Children, Show nth Child - the closest answer to my question
Show and Hide Several Links - this solution makes my head dizzy
My HTML consists of two rows of divs, similar to that simplified representation:
<div class="wrapper">
<div class=".project-tile-normal">some pictures</div>
<div class=".project-tile-normal"></div>
<div class=".project-tile-normal"></div>
<div class=".detail-tile">description</div>
<div class=".detail-tile"></div>
<div class=".detail-tile"></div>
</div>
This is what i have so far coded:
JQUERY
$(document).ready(function(){
$('.project-tile-normal').on("click", function() {
if( $(this).hasClass("active") ) {
$(this).fadeOut(150);
} else {
var itemid = '#div' + $(this).attr('target'); // my own try to get the Element of the divs.
console.log(itemid);
$(this).addClass("active");
$(".detail-tile").removeClass("hidden");
}
});
$('button').on("click", function(){
$(".detail-tile").addClass("hidden");
$(".project-tile-normal").fadeIn(150);
$(".project-tile-normal").removeClass("active");
});
});//document ready
Should i put all the Items in an array and then count it out? Thanks for your help in advance.
First of all remove the . before the class attribute since there is no need of it. As per the jQuery code there is no need of it. If you are using . you need to escape it using \., in the jQuery selector it may be like $('.\\.project-tile-normal') .
Now you can do the rest using index() and eq(),
$('.project-tile-normal').click(function() {
// you can use toggle if you want toggle between the show and hidden
// else use show method
$('.detail-tile').eq($(this).index()).toggle();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="wrapper">
<div class="project-tile-normal">some pictures</div>
<div class="project-tile-normal">1</div>
<div class="project-tile-normal">2</div>
<div class="detail-tile">description</div>
<div class="detail-tile">1</div>
<div class="detail-tile">2</div>
</div>
Firstly note that your class attributes in the HTML should not contain any . characters.
With regard to the JS, you can link elements by index by retrieving the index() from the clicked element then selecting the matching required element using eq(), something like this:
$('.project-tile-normal').click(function() {
var index = $(this).index();
$('.detail-tile').hide().eq(index).show();
});
Working example
You're declaring your classes wrong in your HTML. It'll be project-tile-normal instead of .project-tile-normal. On doing that you'll be finding your events working. Then you can actually follow those tutorials to pull off your desired behavior on project title click.

Distinguishing between two same HTML ID elements using Jquery and css in Wordpress

I know that is a bad practice to have more than HTML elements having same ID. However such is my situation where I need to specifically modify either of them.
I researched around and found about Jquery method 'document.getElementByID' that returns with the first similar element and lets you change it using css. Using that I wrote the code below but it doesn't work.
$(document.getElementById('it_trending-3')).css({"display":"none"});
I have added this code in my wordpress theme using the CSS-JS-PHP wordpress plugin, created a shortcut from the same and then added the shortcode. Can someone please guide me what and where I went wrong?
Also feel free to suggest a different function that would maybe let me specifically point to each of the same ID elements using maybe indexes. Thanks!
Keep a class to the divs you want to change:
<div>
<span id="a" class="test">1</span>
<span id="b" class="test">2</span>
<span>3</span>
</div>
The Jquery would go like this:
$(function() {
var w = $("div");
console.log($('#a').length);
console.log($('body #a').length);
console.log($('#a', w).length);
});
$(".test").first().css({"color":"orange"});
//or
$(".test:first").css({"color":"orange"});
But if you want to select any specific element with the class via an index of sorts, then you would need to do it like this:
var x = $(".test");
$(x[1]).css({"color":"orange"});
You can achieve this in 2 ways.
Based on element's hierarchy or based on class attribute / custom data attribute to the element.
In the below example we have 3 span elements with the same id and we have to apply 3 colors to each of those span elements.
HTML
<div>
<span id="it_trending-3">
Applying css to same Id with hierarchy (span in 1st div)
</span>
</div>
<div>
<span id="it_trending-3">
Applying css to same Id with hierarchy (span in 2nd div)
</span>
</div>
<br /><br /><br />
<span id="it_trending-3" class="testcls">
Applying css to same Id with class
</span>
Applying css using js / jquery based on element hierarchy
JQuery
(function($){
$("div:last #it_trending-3").css("color", "red");
$("div:first #it_trending-3").css("color", "green");
})(jQuery);
Based on class attribute / custom data attribute to the element.
JQuery
(function($){
$("#it_trending-3.testcls").css("color", "blue");
})(jQuery);
JS Fiddle Demo

How to use not selector in jquery with multiple classes as one class

I have in my HTML div with one class tag and one with 2 classes that look like one class.
<body>
<div class="ad-container left">
<div class="ad-container">
<div class="mobile-ad larger">
<div class="mobile-ad">
</body>
Whats the proper way to use the not selector in jQuery to support all 4 div's and not ignore anything else in body.
I currently have
$('body:not(.ad-container,.ad-container.left,.mobile-ad.larger,.mobile-ad)')
It seems to work without any problems.
But something tells me I need to split the left and larger classes into seperate elements by comma.
Something like this
$('body:not(.ad-container,.left,.mobile-ad,.larger)')
Here is the full code:
$(function () {
$('body:not(.ad-container,.ad-container.left,.mobile-ad.larger,.mobile-ad)').on('selectstart', function (event) {
event.preventDefault();
});
});
It's used to disable the left double click selection but still be able to click on ads.
Which one should I use?
I ended up using
$('body :not(.ad-container, .mobile-ad)')

How do I select multiple classes incremented by 1 and their matching children?

I have multiple containers that I need to animate.
Basically: you click on class: box-n (e.g. box-1) and you slideToggle: box-child-n (e.g. box-child-1).
Instead of a click function for every box-n to toggle box-child-n, I want a simple line of code that matches box-n with its children class.
html:
<div class="box-1">Some clickable container</div>
<div class="box-child-1">This should toggle when box-1 is clicked</div>
<div class="box-2">Some clickable container</div>
<div class="box-child-2">This should toggle when box-2 is clicked</div>
Et cetera...
current jquery:
$('.box-1').click(function() { $('.box-child-1').slideToggle() });
$('.box-2').click(function() { $('.box-child-2').slideToggle() });
Sort of desired jquery (allInt function is made up.):
var $n = allInt();
$('.box-' + n).click(function() {
$('.box-child-' + _n).slidetoggle() // local variable to inter alia .box-1
})
I can't seem to think of any solution, so I am asking for help once again.
I appreciate every suggestion you folks give me!
Here's one way to do it that allows for the elements to have other classes besides the ones that you're using to pair them up:
$('div[class*="box-"]').click(function() {
var c = this.className.match(/\bbox-\d+\b/);
if (c)
$('div.' + c[0].replace(/-/, '-child-')).slideToggle();
});
Demo: http://jsfiddle.net/6xM47/
That is, use the [name*=value] attribute contains selector to find any divs with a class attribute that has "box-" in it somewhere. Then when clicked extract the actual class and check that it matches the "box-n" pattern - this allows for multiple (unrelated) classes on the element. If it does match, find the associated "box-child-n" element and toggle it.
Having said all that, I'd suggest structuring the markup more like this:
<div data-child="box-child-1">Some clickable container</div>
<div class="box-child-1">This should toggle when box-1 is clicked</div>
...because then the JS is simple and direct:
$('div[data-child]').click(function() {
$('div.' + $(this).attr('data-child')).slideToggle();
});
Demo: http://jsfiddle.net/6xM47/1/
To just answer your question, this will do the trick :
$("div[class^='box-']").click(function(){
$(this).parent().find('.' + $(this).attr('class').replace('-','-child-') ).slideToggle();
});
jsfiddle here.
Anyway i dont think you use a good approach (you may wrap child into parent div or use ids).

How to select HTML elements which don't have any attributes defined on them?

I need to use jQuery to locate all DIV tags that have no attributes on them and apply a class to each. Here's a sample HTML:
<div id="sidebar">
<div>Some text goes here</div>
<div class="something">something goes here</div>
<div>Another div with no attributes.</div>
</div>
So, I need to take that and turn it into this:
<div id="sidebar">
<div class="myClass">Some text goes here</div>
<div class="something">something goes here</div>
<div class="myClass">Another div with no attributes.</div>
</div>
How do you locate elements of type div that have no attributes via jQuery? Thanks.
Here you go:
$('div', '#sidebar').filter(function () {
return this.attributes.length === 0;
})
Live demo: http://jsfiddle.net/phbU9/
The attributes property returns a list of all attributes set on the element. "Naked" elements have an empty attributes list.
Update: Be sure to read Tim's answer below which provides a solution for older versions of IE, since my own solution doesn't work in IE8 and below.
#Šime's answer is close but doesn't work in IE 6, 7 or 8, where an element's attributes collection has an entry for every possible attribute, not just those specified in the HTML. You can get round this by checking each attribute object's specified property.
Live demo: http://jsfiddle.net/timdown/6MqmK/1/
Code:
$("div").filter(function() {
var attrs = this.attributes, attrCount = attrs.length;
if (attrCount == 0) {
return true;
} else {
for (var i = 0; i < attrCount; ++i) {
if (attrs[i].specified) {
return false;
}
}
return true;
}
});
check this out:
http://jsfiddle.net/thilakar/CHux9/
You need to give some sort of selector, in this case Ive used your side bar but it can be anything. Then get the children that have no class attribute and add a new class. See JSFiddle for the example:
http://jsfiddle.net/HenryGarle/q3x5W/
$("#sidebar").children('div:not([class])').addClass('newClass');
So this would return the 2 elements with no class tag and leave the sidebar and div with the class completely unaffected.
You could use a combination of jQuery's has attribute selector and the not selector. For example:
$('div:not([class], [id])').addClass('myClass');
jsFiddle demonstrating this
With this approach, you need to explicitly specify the attributes to check the presence of. Sime's solution would apply the class to divs that do not have any attributes at all.
To expound upon Tim Down's answer, I recommend checking that the attrs var not null special cases where the html has comment tags, etc.
try $('div:not([class])').addClass('myClass');
it is a general approach because the class will apply to all the div that have no class
$('#sidebar div')` or more general `$('div'); //returns collections of divs
to answer the question:
$('#sidebar div').addClass('myClass');

Categories