:not and :first in jquery - javascript

I am having a jQuery Script to find out the resolution of browser and then change its css.
if ((screen.width>=1024) && (screen.height>=768))
{
alert('Screen size: 1024x768 or larger');
$("link[rel=stylesheet]:not(:first)").attr({href : "detect1024.css"});
}
else
{
alert('Screen size: less than 1024x768, 800x600 maybe?');
$("link[rel=stylesheet]:not(:first)").attr({href : "detect800.css"});
}
});
can you please help me knowing its actual functioning?
what does :not(:first) mean ? Please explain.
Thanks.

actually it means you select every link element with the attribute rel matching the word stylesheet but exclude the first of the found results :)
so if you have three elements in a container and try to select them using :not(:first) you will receive the second and the third one but exclude the first (!) one
not sure if it that is what you want... but if you have more then one link attribute in header and all except the first are set to that href you might (!) end up having the CSS requested / checked against server / cache several times
Media queries (thirtydot's comment) is also a good idea (comment +1)

Try using the an interactive console, such as the one in Chrome's inspector or Firebug in Firefox. Just type in $("link[rel=stylesheet]:not(:first)") and see if any elements are matched.
Edit: Thirtydot's comment about using media queries is a good one as well, and if you are going to have multiple stylesheet's this article may have some useful info.

Related

Cypress img elements attribute checking

I need to check if all images on my page have the Alt attribute. I thought doing the following would do that but it doesn't check things correctly and just gives me an everything is good when I know it's not.
cy.get('img').should('have.attr',
'alt' );
Is there an easy solution other than many go through the page and build a selector for every image?
To check each element, you can use .each:
cy.get('img').each($el => {
cy.wrap($el).should('have.attr', 'alt')
}

Find part of string throughout site and replace with new text

I am still having trouble understanding regex. I am also not even sure if you can target a whole page...but without knowledge of how to format regex, its getting play with it.
I have a trademarked name that appears throughout my page. I'd like to use JS to add a (r) to the end of it every time it appears.
Can jquery/js accomplish this?
$("body").each(function() {
this.innerHTML = this.innerHTML.replace(
'breathe right',
'breathe right(r)');
});
Thanks!
This is a good use case for the CSS :after pseudo-element:
CSS
.product-name:after {
content: " \00AE"; /* add restricted symbol after every element with the product-name class */
}
HTML
<span class="product-name">My Product</span>
Working Demo
The easiest way is to wrap your product name in a span and tag it with a class. I'm not sure if that's less work that just adding the symbol to your markup to begin with, though.
The benefit of this approach is it would allow you to easily apply other styles to your product name, like bolding the text or changing the font color.
You can read more about the :after pseudo-element here.
Yes, but it won't be efficient if you tell jQuery to search the entire document. To make it efficient, you'll need to have jQuery get a specific location to search if you want any efficiency in it.
You don't need jQuery :
document.body.innerHTML = document.body.innerHTML.replace(/breathe right/g, 'breathe right(r)')

Removing data attributes from HTML using jQuery

Can't seem to get this one to work...
I have a page that hides certain links. When the DOM is loaded, I'm using jQuery to toggle some of those elements. This is driven by using a data attribute like so:
<div class="d_btn" data-usr='48'>
<div class="hidden_button">
Then, I have the code:
$.each($(".d_btn"), function() {
var btn = $(this).data('usr');
if ( btn == '48' ){
$(this).children('.hidden_button').toggle();
}
The above all works as planned. The problem is that I am trying to remove the data-usr from the class .d_btn once the if statement is evaluated. I've tried the following and nothing works (i.e., after the page is loaded, the source still shows the data-usr attribute:
$(this).removeAttr("data-usr");
$(this).removeData("usr");
I've been working on this for a couple of hours now and...nothing! Help is greatly appreciated!
UPDATE
I've tried the great suggestions of setting the data attribute to an empty string but I'm still not getting the desired result.
To explain a little further, The reason I'm trying to remove the attribute is so when an ajax response adds another item to the page, the previously added items would already have the button either shown or hidden. Upon AJAX response, I'm calling the same function once the DOM is loaded.
Currently, when something is added via AJAX, it toggles all the buttons (showing the ones that were hidden and vice versa.) Ugh...
I'm also fully willing to try alternatives to my approach. Thanks!
UPDATE
Well, the light bulb just flashed and I am able to do what I want to do by just using .show() instead of .toggle()
Anyway, I'd still like to find an answer to this question because the page will be potentially checking hundreds of items whenever something is added - this seems horribly inefficient (even for a computer, hahaha.)
Why don't you set the value to a random value or empty variable instead if removeAttr does not work..
$(this).attr("data-usr" , '');
$(this).prop("data-usr" , '');
Changing the DOM doesn't affect the source. It affects the DOM, which you can view with the Inspector/Developer Tools. Right click => View Source will give you the original source of the page, not the actual current source as modified by JavaScript.
Set it to a blank string:
$(this).attr("data-usr", "");
I second what Kolink said: check the DOM, not the source. (Chrome: Ctrl + Shift + i).
As others have stated. Checking the source will only show the original unedited source for the webpage. What you need to do is check the DOM using developer tools.
I've just checked everything in Chrome's inspector on jsfiddle here and the attribute is definitely being removed as well as the data.

jQuery Chosen plugin without search field

Not sure if this has been covered somewhere, but I couldn't find it in the documentation, and was wondering if it'd be possible to not include the search input box with the jQuery chosen plugin (used to style select inputs). Specifically I'd like to use the standard select one without it.
http://harvesthq.github.com/chosen/
Just a quick follow-up: I noticed that in function
AbstractChosen.prototype.set_default_values
a variable is read from
this.options.disable_search
So you can disable the search-field with
jQuery('select').chosen( {disable_search: true} );
without using a fixed-number threshold.
$(".chzn-select").chosen({disable_search_threshold: 3});
If the number of element of the select is smaller than disable_search_threshold (here 2 and less), the search box will not display.
Well I tried with the documentation as well and no luck, so I finally fixed to this
$('.chzn-search').hide();
I do the above after I call chosen.
Hope this helps
I add a class to my stylesheet.
.chzn-select { display: none }
Alternatively, for individual elements, I specify the element and append _chzn to target it.
#element_chzn .chzn-select { display: none; }
Note that: chosen will convert hyphens in your element ids and classes to underscores, so to target element-id you need.
#element_id_chzn .chzn-select { display: none; }
Newer versions of jquery chosen gives you option to disable search input with in dropdown.
$(".chzn-select").chosen({
disable_search: true
});
Older versions do not support this option. Some how if you are strictly not allowed to use newer version than you can use
$(".chzn-select").chosen({
disable_search_threshold: 5
});
it will hide the search box if results are less than 5, best to use with gender type dropdowns. There is another way to fix this and that is;
$(".chzn-select").chosen();
$(".chzn-select").hide();
Call hide immediately after initialization, don't know why this tricks works but it is doing what you want!
I suggest you to use the latest version so you have access to latest options.
Hope it works for you!
Use this code to disable it:
jQuery('select').chosen( {disable_search: true} );
and don't forget to hide it, otherwise it will still be working on mobile !
.chzn-search{display: none}
The disable_search_threshold option hides the search box for single select dropdowns. The number passed in specifies how many items you want to allow before showing the search box. If you don't want the searchbox, just set it to a higher number than the amount of items it will ever contain.
$('#myDropDown').chosen({ disable_search_threshold: 10 });
$('select').chosen( {disable_search: true} );
Since none of the chosen-settings for hiding the search-field for multiple selects seemed to be working, I hacked the chosen.jquery.js in line 577 to:
<li class="search-field"><span class="placeholder">' + this.default_text + '</span></li>
(Span instead of the input field). Needed to comment out this line, too
this.search_field[0].disabled = false;
Working fine for me - even though its not the best practice to hack the code.
With the latest Version of chosen only that works for me:
$('ul.chosen-choices li.search-field').hide();
I used jQuery('select').chosen( {disable_search: true} ); but on chrome profiler, the method search_field_scale was called anyway and eat a lot of the performance.
So I remove the method and all the calls to him and replaced with this.search_field.css({'width': '100%'}) on show_search_field_default and replace style=25px with style:100%
and than
this.search_field.css({ 'width': '23px' }); result_select because of the "data-placeholder"
working fine for me.
disable_search:true,
Here is the document for chosen jquery plugin

Problem with jQuery - error when trying to find 2 tags

I have the following DOM structure:
/*:DOC += <div id='testDiv' class='testDivClass'><div id='innerTestDiv'></div></div><span id='testSpan' class='testSpanClass'><span id='innerTestSpan'></span></span>
Now I tried to run jQuery select against them as follow. The first one returned alright, but the second one failed:
// works
var result = $('#testDiv')[0];
alert(result.id);
// failed: id is null or not an object
var result2 = $('#testSpan')[0];
alert(result2.id);
I tried selecting id instead of class and got the same results.
My question is: how can I get the second select to work? Is there some sort of invisible iterator/pointer in jQuery which I need to reset to the beginning of the DOM before the second select?
Thanks.
EDIT: Ok this is the official "does not work" version. testDiv matched, but testSpan did not, hence I got an error saying id is null or not an object error in the second alert.
UPDATE: I did a test by swapping testDiv and testSpan in the html. Now BOTH select failed.
UPDATE2: I have changed the html back to what it used to look like. I'm using JsTestDriver to write up the test, but it is actually not calling anything at the moment. The actual html looks messier than this (more nested tags). I'm trying to get this simplified version to work first. It appears that jQuery was able to get into the first select, whether it'll be span or div, but couldnt get out of it to do the second select. I've replaced jQuery.js and jsTestDriver.jar to no avail.
Thanks.
The .className selector matches by class, not ID.
Therefore, $(span.testSpan) won't match any elements.
You need to change it to $('span.testSpanClass') ot $(span#testSpan') (using the #id selector, which matches ID).
For more information, read the documentation.
I don't know why, but for me your code worked well.
I added $(document).ready(function() { before that code, and when I opened the test page, the alert box showed up perfectly, both of them! I don't know when do you want this alert box showed, but if it is when visitor open the page, just add that code. Otherwise, add
function objectid() {
var result = $('#testDiv')[0];
alert(result.id);
var result2 = $('#testSpan')[0];
alert(result2.id);
}
That code worked well for me, too.
PS: Sorry if you don't understand my bad english.
More than likely, there is something else wrong with the HTML you're actually using. Since you're posting only a tiny bit of the html, we can't actually test your problem. Post the entire page, or at least the smallest piece of it that actually has the problem when you run your test.
I tested the jQuery code you reported on JS Bin, and the code worked fine. As the code is very basic, I don't think the problem is caused by the version of jQuery used.
What I ended up doing is wrapping the entire html with a div or span tag. I found that jQuery could not get out of a div/span tag once it gets into one (in my above example), so I just make it to go into a div/span tag once.
Not sure whether this is a patch or ugly fix, but it solved my problem for now.
Thanks for all the help!
Use "#" to select by id, use "." to select by class...

Categories

Resources