I need some help writing a function with multiple if statements (unless there is a better method). I basically want to truncate text length based on window size. So if the viewport is less than 400px and the text length is greater than 35, then truncate using this method below...
$('option').each(function () {
var text = $(this).text();
if (text.length > 35) {
text = text.substring(0, 35) + '...';
$(this).text(text);
}
});
The function for window resize (basically combine above with below):
$(document).ready(function(){
if($( window ).width() < 400){
//do something;
}else{
//do something else;
}
});
$( window ).resize(function() {
if($( window ).width() < 400){
//do something;
}else{
//do something else;
}
});
Did a little more research and got it working with this code:
$(document).ready(myfunction);
$(window).on('resize',myfunction);
$('option').each(myfunction);
function myfunction() {
var text = $(this).text();
if (text.length > 35 == ($(window)).width() < 400) {
text = text.substring(0, 35) + '...';
$(this).text(text);
}
}
I wonder if/how a math function could calculate viewport width as a range and change truncation up to a maximum breakpoint?
I ended up answering my own question. So, I am posting it here incase someone else has a similar need or can improve what I have done...
Basically, I am truncating select option boxes by applying character length and window width. This prevents very lengthy option text to flow past its container and beyond the screen. I am sure there is a more efficient way to code this, but my tests appear to be successful which works for now.
/**
* Truncate lengthy option text in select boxes
*/
var defaultString=$('option').text();
function checkWidth() {
if($(window).width() > 600){
$('option').each(function(i){
len=$(this).text().length;
if(len>65)
{
$(this).text($(this).text().substr(0,65)+'...');
}
});
return false;
}
if ($(window).width() > 451 && $(window).width() < 599 ) {
$('option').each(function(i){
len=$(this).text().length;
if(len>50)
{
$(this).text($(this).text().substr(0,50)+'...');
}
});
return false;
}
if($(window).width() < 450){
$('option').each(function(i){
len=$(this).text().length;
if(len>35)
{
$(this).text($(this).text().substr(0,35)+'...');
}
});
return false;
}
}
checkWidth();
$(window).resize(checkWidth);
$(document).ready(checkWidth);
The last three lines bind 'checkWidth' and window 'resize' (which can also be 'width' or 'height') depending upon what you are achieving. Binding must be done before you can execute the function events.
Related
I have this little piece of code that filters through a list of results and hides the divs that don't match. I am writing this for a PhoneGap iOS application. It works fine on Android, but on iOS for some reason it hides the entire search field as well after typing a few characters, not just the results.
Any idea why? I've stripped it down to almost only the HTML code and jQuery and it's still happening. I tried commenting out the $(this).hide(); part and it stops hiding the search field, so I assume somehow that's the culprit, but I can't figure out why or how to fix this. Been at it for 10 hours straight. Any ideas? Maybe I can target the results some other way?
$('#box_search').keyup(function() {
var valThis = $(this).val().toLowerCase();
if (valThis == "") {
$('#listing-results > .listing_container').show();
} else {
$('#listing-results > .listing_container').each(function() {
var text = ($(this).find('.listing_results_text_name').text() + $(this).find('.listing_results_text_name').data("alt")).toLowerCase();
if (text.indexOf(valThis) >= 0) {
$(this).show();
} else {
$(this).hide();
}
});
};
});
obviously I cant see the html but sometimes it helps to clean the code and just change the logic slightly
var box_search = function(e){
var myIndex = $(this).val();
val = (!myIndex || myIndex==='')?false:myIndex;
if(!myIndex){
$('#listing-results > .listing_container').show();
return;
}
//
$('#listing-results > .listing_container').each(function() {
var text = $(this).find('.listing_results_text_name').text() +
$(this).find('.listing_results_text_name').data("alt")
text = (!text || text==='')?false:text;
text = text.toLowerCase();
if(text.indexOf(myIndex.toLowerCase()) >= 0){
$(this).show();
return;
}
$(this).hide();
});
} //end of function
$('.box_search').keyup(box_search);
I am trying to create a Navigation Bar that slides in and out when clicked on using JavaScript and Greensock. For some reason, the on click action is randomly not working when clicked on at different sizes but sometimes it works perfectly fine.
My code is below, you can find a live example of this navigation at: http://www.kramergraphicdesign.com/Maura_Website/
var resize = function(){
var viewportWidth = $(window).width();
var lastLiWith = $('#logo').width();
console.log(openOrShut + " this is the true false var");
if ($(window).width() >= 0 && $(window).width() <= 639 ) {
console.log("mobile");
$("#logo, #close, .arrow-right").click(function()
{
console.log("mobile-click");
if(openOrShut === false)
{
TweenLite.to("#custom-nav",".5",{x:viewportWidth-lastLiWith});
openOrShut = true;
}
else{
TweenLite.to("#custom-nav",".5",{x:0});
openOrShut = false;
}
});
}
else if ($(window).width() >= 640 ) {
console.log("tablet");
$("#logo, #close, .arrow-right").click(function()
{
console.log("tablet-click");
if(openOrShut === false)
{
TweenLite.to("#custom-nav",".5",{x:400});
openOrShut = true;
}
else{
TweenLite.to("#custom-nav",".5",{x:0});
openOrShut = false;
}
});
}
else if ($(window).width() >= 1025 && $(window).width() <= 10000 ) {
console.log("dekstop");
$("#logo, #close, .arrow-right").click(function()
{
console.log("desktop-click");
if(openOrShut === false)
{
TweenLite.to("#custom-nav",".5",{x:400});
openOrShut = true;
}
else{
TweenLite.to("#custom-nav",".5",{x:0});
openOrShut = false;
}
});
}
};
$(document).ready(resize);
$(window).resize(function(){
resize();
});
First of all, the resize event can occur an awful lot, especially during a drag to resize the window. This means two things:
Minimise the amount of work you do so it runs fast, or debounce the function (e.g. using Lodash) so it only runs after you stop receiving resize events for a short time.
More importantly, you are adding a new click handler every single time.
So the reason it "randomly" doesn't do anything is that whenever you click, you actually run your function to toggle the menu many, many times if you have previously resized the window at all. If that number of times happens to be even, then there is no net effect.
There are probably a number of ways to fix this, but here are two:
Attach a click handler once, but check the width inside the handler to determine how far to animate it to / how to respond differently to different sizes.
Unregister existing click events first (using jQuery's .off()) before re-adding them, so there is only ever the one handler registered. I recommend using an event namespace so you can deregister everything on the namespace at once.
Bonus observation: your condition for the tablet widths means the desktop code will never run, because there is no <= 1024 condition for the tablet block.
How to switch hover and click when window size change
function checkWidth() {
var windowsize = $window.width();
if (windowsize > 480) {
$('#clickPoint').on('click', function(){
......//code
});
}else {
$('#clickPoint').on('hover',function(){
......//code
});
}
}();
$(window).resize(checkWidth);
However I found hover is always on, so I had to change to this way
var windowsize = $window.width();
if (windowsize > 480) {
$('#clickPoint').on('click', function(){
......//code
});
}else {
$('#clickPoint').off('click', function(){
......//code
});
$('#clickPoint').on('hover',function(){
......//code
});
}
}();
but still doesn't work properly, if someone has a better solution?Thanks
Take a close look at $window.width(). I suspect that. Try changing it to $(window).width(). Make changes to the code that you provided at the top. Because the code at the bottom looks messed up.
Also make sure to check the window width by using an alert or log. Just to make sure that the if statement is working right.
Try it like this
var permit=2;
$('#clickPoint').on('click', function(){
if(permit==0)
{
......//code
}
});
$('#clickPoint').on('hover',function(){
if(permit==1)
{
......//code
}
});
function checkWidth() {
var windowsize = $(window).width();
if (windowsize > 480) {
permit=0;
}else {
permit=1;
}
}
$(window).resize(checkWidth);
I want to add some condition in jquery like media queries in CSS, anyone can help me with this? I try the code below but is not working:
jQuery(document).ready(function(){
if (jQuery(window).width() >= 320) && (jQuery(window).width() <= 479) {
}
if (jQuery(window).width() >= 480) && (jQuery(window).width() <= 567) {
}
});
You have parentheses around your individual conditions, but not around the if conditions as a whole.
Try this:
jQuery(document).ready(function(){
alert("Running");
alert(jQuery(window).width());
if ((jQuery(window).width() >= 320) && (jQuery(window).width() <= 479)) {
alert('Small screen');
} else
if ((jQuery(window).width() >= 480) && (jQuery(window).width() <= 567)) {
alert('Large screen');
} else {
alert("Biggest screen");
}
});
Note the extra parentheses after if and before {
You actually don't need mediaqueries in JS to do your task the right way. First of all: how to work with media queries in JS. You can use matchMedia. Here is a brief documentation.
Here is a simple example:
var smallMatcher = matchMedia('(max-width: 480px)');
var biggerMatcher = matchMedia('(max-width: 1024px)');
var run = function(){
if(smallMatcher.matches) {
//run code for small
} else if(biggerMatcher.matches){
//run code for bigger
} else {
//run code for else
}
};
//now run it
run();
//in case you need to dynamically change on resize
//use addListener
smallMatcher.addListener(run);
biggerMatcher.addListener(run);
But as said, you don't need this. What you actually need to do is simple separation of concerns. Don't mix your behavior with your CSS. Simply add focus/blur or focusin/focusout events, the add or remove a class and do everything else in CSS.
This should result in clean and simple code, here is an example:
$('#searchbox')
.on('focus', function(){
$(this).closest('form').addClass('focused-field');
})
.on('blur', function(){
$(this).closest('form').removeClass('focused-field');
})
;
Everything else can and should be handled in CSS.
And In case you need the modify the style for the input button also if the button itself is focused and not only the search input you can see the following fiddle.
Can I use resize and scroll handlers together like this:
$(window).on('scroll resize',function(){
if($(window).width() == "1024"){
if($(window).scrollTop() == 400){
$('div.foo').addClass('red') ; //to change to red color
}
}
}) ;
The way I used , is it the correct way, what are the implications of this ? Is there a better way to incorporate both the handlers ? Thanks for your reply. Please let me know if you need a simulation of the above code. Thank you !
do this
var handler = function(){
if ($(window).width() == "1024") {
if ($(window).scrollTop() == 400) {
$('div.foo').addClass('red') ; //to change to red color
}
}
};
$(window).on('scroll',handler).on('resize',handler);