Am I using the correct jQuery syntax? - javascript

I have the following code -
$(window).resize(function () {
if ($(window).width() >= 1023) {
for (var i = 0; i < seatInfo.length; i++) {
if (seatInfo[i].data == 'true') {
document.getElementById('Btn1').style.visibility = "visible";
break;
} else {
document.getElementById('Btn1').style.visibility = "hidden";
}
}
if (nameInfo[0].data == "true") {
document.getElementById('Btn2').style.visibility = "visible";
}
}
if ($(window).width() <= 1022) {
document.getElementById('Btn2').style.visibility = "hidden";
}
});
Is this is the correct way to write it? I notice that it contains a JavaScript and jQuery mix.

If you are specifically asking about the jQuery syntax then the answer is no. You are using the native JavaScript methods instead of the much shorter jQuery methods.
Take a look at some jQuery selectors. For instance:
An element with an id attribute of foo can be found using jQuery's id attribute selector #:
var element = $( "#foo" ); // match the element
Changing an elements visibility attribute is the same as changing any other css attribute:
element.css( "visibility", "visible" ); // change css properties
A great feature of jQuery is it's many shortcut methods. There are a few shortcut method to display and hide elements (and toggle them):
element.show()
element.hide()
element.toggle()

Why stop using jQuery half-way?
For document.getElementById('Btn1') use $('#Btn1').
For .style.visibility = "visible" use .show() (or, if you want to be very precise, .css('visibility', 'visible'))
There is lots of good documentation on the official jQuery site.

You can use $('#some-id').hide() and $('#some-id').show(). Instead of document.getElementById('some-id') with style.visibility = "visible" or style.visibility = "hidden".

you can use .css from jquery and set it as json structure to define one or multiple CSS attributes, this is more easier for me to remember.
$('#Btn1').css({
'property': 'value',
'property': 'value'
});
or just use it like this for a single attribute
var btn1 = $('#Btn1'),
btn2 = $('#Btn2'),
window = $(window);
window.resize(function () {
if (window.width() >= 1023) {
for (var i = 0; i < seatInfo.length; i++) {
if (seatInfo[i].data == 'true') {
btn1.css('visibility','visible');
break;
} else {
btn1.css('visibility','hidden');
}
}
if (nameInfo[0].data == "true") {
btn2.css('visibility','visible');
}
}
if (window.width() <= 1022) {
btn2.css('visibility','hidden');
}
});

Related

converting javascript to jquery function not correctly working

I am trying to convert a small script from javascript to jquery, but I don't know where I should be putting the [i] in jquery?. I am nearly there, I just need someone to point out where I have gone wrong.
This script expands a search input when focused, if the input contains any values, it retains it's expanded state, or else if the entry is removed and clicks elsewhere, it will snap back.
Here is the javascript:
const searchInput = document.querySelectorAll('.search');
for (i = 0; i < searchInput.length; ++i) {
searchInput[i].addEventListener("change", function() {
if(this.value == '') {
this.classList.remove('not-empty')
} else {
this.classList.add('not-empty')
}
});
}
and converting to jquery:
var $searchInput = $(".search");
for (i = 0; i < $searchInput.length; ++i) {
$searchInput.on("change", function () {
if ($(this).value == "") {
$(this).removeClass("not-empty");
} else {
$(this).addClass("not-empty");
}
});
}
Note the key benefit of jQuery that it works on collections of elements: methods such as .on automatically loop over the collection, so you don't need any more than this:
$('.search').on("change", function() {
this.classList.toggle('not-empty', this.value != "");
});
This adds a change event listener for each of the .search elements. I've used classList.toggle as it accepts a second argument telling it whether to add or remove the class, so the if statement isn't needed either.

I am trying to convert jquery into vanilla javascript

This is probably an easy solution but right now I can't figure out how to make it work
$(".a").click(function () {
if ($("#btnCollapse").css('display')!='none')
$("#btnCollapse").click();
});
Then I tried using vanilla js, I know I am missing something....
var anchor = document.querySelectorAll(".a");
var button = document.querySelectorAll("#btnCollapse");
function collapseNav() {
anchor.addEventListener('click', function() {
button.style.display="none"
});
button.click();
}
querySelectorAll returns a nodelist so you need to loop through its result.
For the #bntCollapse use querySelector, it returns as single element. For elements with an id, and if you need to find many, you can use getElementById, which is faster than querySelector
To get the style, use window.getComputedStyle as it will return a style being set using external CSS as well, which element.style.display won't.
var anchors = document.querySelectorAll(".a");
for (var i = 0; i < anchors.length; i++) {
anchors[i].addEventListener('click', function(e){
var btn = document.querySelector("#btnCollapse");
if (window.getComputedStyle(btn,null).getPropertyValue("display") != 'none') {
btn.click();
}
})
}
Note, you can use foreach to loop the elements, though based on how, in IE, Edge and Safari it might not work, so test it thoroughly, therefore I used a for..loop for maximum browser support.
Direct conversion of your "jQuery" code:
if (button.style.display != 'none')
button.click();
It can be done using closure-in-loop,
var anchor = document.querySelectorAll(".a");
var button = document.querySelectorAll("#btnCollapse");
Array.from(anchor).forEach(a => {
a.addEventListener('click', function() {
if(button.style.display!="none"){
button.click();
}
});
});
querySelectorAll() returns a collection of elements, not a single one, hence you need to loop over it. The button has an id so you can select it using querySelector() to get a single instance back.
You also have no collapseNav() function in the jQuery version so your event handler will be added on load.
Finally the logic is not the same. In the jQuery you only click the button if it's display is not none. Try this:
var anchor = document.querySelectorAll(".a");
var button = document.querySelector("#btnCollapse");
anchor.forEach(function(el) {
el.addEventListener('click', function() {
if (button.style.display != 'none')
button.click();
});
});

jQuery check if class exists or has more than one class

I have a class js-bootstrap3 that is generated by a cms. What I need to do is check if the containing element just has js-bootstrap3and .unwrap() the contents, but if the element has multiple classes which include js-bootstrap3 then I'm trying to just remove that class.
jsFiddle
$('.jsn-bootstrap3').each(function(){
if( $(this).attr('class') !== undefined && $(this).attr('class').match(/jsn-bootstrap3/) ) {
console.log("match");
$(this).contents().unwrap();
$(this).removeClass('jsn-bootstrap3');
}
});
This just seems to detect any element with js-bootstrap3as a class and unwraps it.
this.className is a string with all of the classes for the element (space delimited), so if it's not just "jsn-bootstrap3" you know it has more than one class:
$('.jsn-bootstrap3').each(function(){
if( $.trim(this.className) !== "jsn-bootstrap3") {
// Just jsn-bootstrap3
$(this).contents().unwrap();
} else {
// More than just jsn-bootstarp3
$(this).removeClass('jsn-bootstrap3');
}
});
Dependeing on the browsers you need to support element.classlist (IE10+) might or might not be what you need.
classList returns a token list of the class attribute of the element.
classList is a convenient alternative to accessing an element's list of classes as a space-delimited string via element.className. It contains the following methods:
Otherwise you're looking at splitting the className into an array like so to count the values:
var classes = element.className.split(" ");
Building on your example you could do something liket his:
$('.jsn-bootstrap3').each(function(i, el){
if( el.className.indexOf('jsn-bootstrap3') != -1 ) {
console.log("match");
if ( el.className.split(" ").length > 1 ) {
$(this).removeClass('jsn-bootstrap3');
} else {
$(this).contents().unwrap();
}
}
});
Try this code.
$(document).ready(function(){
$('.jsn-bootstrap3').each(function(){
var classes = $(this).attr('class');
var new_cls = classes.split(' ');
if( new_cls.length > 1 ){
$(this).removeClass('jsn-bootstrap3');
} else {
$(this).contents().unwrap();
}
});
});

Can I hide a repeating string of HTML via javascript?

I don't know how to do this but I need to hide a repeating (50 times in one page) string of html from being displayed in the browser.
The offending line of html is something like:
<li>Empty</li>
I know this would be a hack but I can't alter the source of this list content.
Is there some javascript code I could put in the head of my document which could hide this string?
Many thanks,
Dar.
You can use :contains to get elements based on their content.
HTML :
<li>Empty</li>
jQuery :
$('a:contains("Empty")').css('display', 'none');
Example : http://jsfiddle.net/9z5du/285
You could hide them without any scripting by setting;
.extLink {
display: none;
}
This will work whether or not JavaScript is enabled and it will mean they won't display even for a flash while the document loads.
If it is specifically the actor links, you can target those too - or if it is both you can make the rule cover both. Let me know if your requirement is more specific.
a[href=actor] {
display: none;
}
If you want to hide them based on the content, you will need to use JavaScript.
var clearEmptyActorLinks = function () {
var externalLinks = document.getElementsByClassName('extLink');
for (var i = 0; i < externalLinks.length; i++) {
if (externalLinks[i].innerHTML === 'Empty') {
externalLinks[i].parentNode.style.display = 'none';
}
}
};
window.onload = clearEmptyActorLinks;
Example: http://jsfiddle.net/ZnK59/
Like this?
window.onload = function () {
var n, hiddens = document.getElementsByClassName('extLink');
for (n = 0; n < hiddens.length; n++) {
if (hiddens[n].innerHTML === 'Empty')
hiddens[n].style.display = 'none';
}
if (hiddens[n].href === 'actor') {
hiddens[n].parentElement.style.display = 'none';
}
}
}
Based on jQuery:
$(function() {
var i = 0;
$('li').each(function() {
if (i == 0) {continue;i++}
$(this).remove();
i++;
});
});
I'm not sure what are you looking for.
Removing empty tags:
$(function() {
var i = 0;
$('li').each(function() {
if (i == 0) {continue;i++}
var $obj = $(this);
if ($obj.find('a').text() == 'Empty') {
$obj.remove();
}
i++;
});
});

Toggle text on button tag

I have a show hide table rows feature but would now like to change my text.
<script language="javascript" type="text/javascript">
function HideStuff(thisname) {
tr = document.getElementsByTagName('tr');
for (i = 0; i < tr.length; i++) {
if (tr[i].getAttribute('classname') == 'display:none;') {
if (tr[i].style.display == 'none' || tr[i].style.display=='block' ) {
tr[i].style.display = '';
}
else {
tr[i].style.display = 'block';
}
}
}
}
The html is as follows...
<button id="ShowHide" onclick="HideStuff('hide');>Show/Hide</button>
I want to toggle the "Show/Hide" text. Any ideas?
$('#HideShow').click(function()
{
if ($(this).text() == "Show")
{
$(this).text("Hide");
}
else
{
$(this).text("Show");
};
});
Alternative, the .toggle() has an .toggle(even,odd); functionality, use which ever makes most sense to you, one is slightly shorter code but perhaps less definitive.
$('#HideShow').toggle(function()
{
$(this).text("Hide");
HideClick('hide');
},
function()
{
$(this).text("Show");
HideClick('hide');
}
);
NOTE: you can include any other actions you want in the function() as needed, and you can eliminate the onclick in the markup/html by calling your HideClick() function call in there. as I demonstrate in the second example.
As a follow-up, and to present an alternative, you could add CSS class to your CSS
.hideStuff
{
display:none;
}
THEN add this in:
.toggle('.hideStuff');
or, more directly:in the appropriate place.
.addClass('.hideStuff');
.removeClass('.hideStuff');
Use jQuery something like this might work:
$('ShowHide').click(function(){
if ( $('hide').css('display') == 'block' )
$('ShowHide').val("Hide");
else
$('ShowHide').val("Show");
});
I just wrote that from the top of my head though, so you might need to do some changes, you can read more about the css jquery api here. And all I did was using anonymous functions
I would recommend using jquery but you can just use javascript's document.getElementById method
in your function:
function HideStuff(thisname) {
tr = document.getElementsByTagName('tr');
for (i = 0; i < tr.length; i++) {
if (tr[i].getAttribute('classname') == 'display:none;') {
if (tr[i].style.display == 'none' || tr[i].style.display == 'block') {
tr[i].style.display = 'none';
}
else {
tr[i].style.display = 'block';
}
}
}
if (document.getElementById("ShowHide").value == "show") {
document.getElementById("ShowHide").value = "hide";
}
else {
document.getElementById("ShowHide").value = "show";
}
}
Although, I would probably pass in this instead of the text 'hide' in the function call. then yon can do it like zaph0d stated. Its a bit cleaner then.
Not sure why you are passing thisname into the JS as this is not currently getting used.
If you change the call to:
<button id="ShowHide" onclick="HideStuff(this)">Show</button>
and then in the js you can change the text fairly easily:
if (this.value == 'Show') {
this.value = 'Hide'
}
else {
this.value = 'Show';
}

Categories