I have a list of elements that content is generated with php from a database (I can multiply their values). I want them to have the width of the widest element - it should be updated on page load and click on select tag (multiplying the values). The script works on page load, but it's not updating the width when I'm clicking the select tag. Also, when the widest element shrinks, the width is not shrinking as it should, but staying the same as before.
<head>
<script src="script.js" defer></script>
</head>
<select class="multiply_ing">
<option value="0.5">0.5x</option>
<option value="1" selected>1x</option>
<option value="5">5x</option>
<option value="10">10x</option>
</select>
// it looks like this - data-val generated from php <p class='ing_wght' data-val='$ing_weight'></p>
<p class='ing_wght' data-val='33'></p>
<p class='ing_wght' data-val='54'></p>
<p class='ing_wght' data-val='7312'></p>
<p class='ing_wght' data-val='6'></p>
// js/jquery code for multiplying is in the same file (above this one) as the script to change the width
$(".multiply_ing").on("click", function(){
ingWidth();
});
$(window).on("load", function(){
ingWidth();
});
function ingWidth(){
let maxWidth = 0;
let widestIngWght = null;
let ingWght;
$(".ing_wght").each(function(){
ingWght = $(this);
if(ingWght.width() > maxWidth){
maxWidth = ingWght.width();
widestIngWght = ingWght;
}
});
$(".ing_wght").css("width", maxWidth);
console.log(maxWidth);
}
How can I fix these problems?
Change:
$(".multiply_ing").on("click", function(){
ingWidth();
});
To:
$(document).on("change", ".multiply_ing", function(){
ingWidth();
});
This should work.
So I found the solution. I had to add an if statement that removes the width from the class $(this) if it's wider or equal to previously defined max width.
$(".multiply_ing").on("click", function(){
ingWidth();
});
$(window).on("load", function(){
ingWidth();
});
function ingWidth(){
let maxWidth = 0;
let widestIngWght = null;
let ingWght;
$(".ing_wght").each(function(){
ingWght = $(this);
if(ingWght.width() >= maxWidth){
ingWght.width("");
}
if(ingWght.width() > maxWidth){
maxWidth = ingWght.width();
widestIngWght = ingWght;
}
});
$(".ing_wght").css("width", maxWidth);
}
Maybe it will help someone in the future.
Related
My page header bar has a + and - to use to increase and decrease the font (using the function below)...
This all works correctly. I'm storing the new font size value in a cookie.
The desired outcome is if you a) refresh the page, or b) go to a different page on the site, it sets the font size to what was stored... however, this is not the case.
Here is my code bits... (using a script.js file)
var resize = new Array('.resizable');
$(document).ready(function() {
resize = resize.join(',');
var resetFont = $(resize).css('font-size');
$(".reset").click(function(){
$(resize).css('font-size', resetFont);
setFontSizeCookieValue(resetFont);
});
//increases font size when "+" is clicked
$(".increase").click(function(){
event.preventDefault();
changeFontSize(true);
return false;
});
//decrease font size when "-" is clicked
$(".decrease").click(function(){
changeFontSize(false);
return false;
});
// set the page font size based on cookie
setPageInitialFontSize();
});
function setPageInitialFontSize() {
var currentSize = $(resize).css('font-size');
if (currentSize !== getFontSize()) changeFontSize();
};
// font size changer
function changeFontSize(increase) {
var currentFontSize = getFontSize(); //getFontSize gets the cookie value or, if not set, returns 16
var currentFontValue = parseFloat(currentFontSize, 10);
var newFontSize = currentFontSize;
if (increase !== undefined) newFontSize = Math.floor((increase) ? currentFontValue * 1.2 : currentFontValue * 0.8);
$(resize).css('font-size', newFontSize);
setFontSizeCookieValue(newFontSize);
};
I'm not showing the 'cookie' code calls (set and get) as they are working properly setting/getting the cookie values.
When you click the + or - buttons, they call the changeFontSize function with the correct parameter value. When the page loads/refreshes, setPageInitialFontSize() is being called...
Stepping through setPageInitialFontSize, it tests the current size (16px) with the getFontSize call (19) and flows through changeFontSize, which does everything its supposed to do, but it's like
$(resize).css('font-size', newFontSize);
doesn't actually do anything here...
So I could use any help trying to figure out why this isn't working...
I guess this is what you are trying to achieve , use this code or follow along with your code just see what you are missing as i cant see cookies part in your code, check here the working code
https://jsbin.com/wofogejiye/edit?html,js,console,output
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Increase and Decrease Font Using Jquery and CSS</title>
<script type="text/javascript" language="javascript"
src="http://code.jquery.com/jquery-latest.js"><
/script>
<script type="text/javascript">
</script>
</head>
<body>
<input type="button" class="increase" value=" + ">
<input type="button" class="decrease" value=" - "/>
<input type="button" class="resetMe" value=" = ">
<div>Click Respected Buttons to Increase or Decrease the Font </div>
</body>
</html>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script>
$(document).ready(function(){
var originalSize = getFontSizeLocalStorage()
// reset
$('div').css('font-size', originalSize);
$(".resetMe").click(function(){
$('div').css('font-size', originalSize);
});
$('div').css('font-size');
// Increase Font Size
$(".increase").click(function(){
var currentSize = getFontSizeLocalStorage()
var currentSize = parseFloat(currentSize)*1.2;
$('div').css('font-size', currentSize);
addToLocalStorage(currentSize)
return false;
});
// Decrease Font Size
$(".decrease").click(function(){
var currentSize =getFontSizeLocalStorage()
var currentSize = parseFloat(currentSize)*0.8;
$('div').css('font-size', currentSize);
addToLocalStorage(currentSize)
return false;
});
});
function addToLocalStorage(fontSize){
window.localStorage.setItem("fontSize",fontSize)
}
function getFontSizeLocalStorage(){
if( window.localStorage.getItem("fontSize")){
return window.localStorage.getItem("fontSize")
}
return $('div').css('font-size')
}
</script>
I have been wondering why the following jquery script is not beeing run every 5 seconds.
The correct height of the DIV ".leistung" (there are multiple ".leistung" div's with different lenght of text thats why every block has to have the same height) is beeing applied on load. But the function is not beeing run every five seconds for some reason.
Does anyone know why this is happening?
<section class="leistung">
<div class="leistung-image">
<img src="http://www.myfico.com/Images/sample_overlay.gif"/>
<div class="leistung-image-titel">
<span>Title</span>
</div>
</div>
<div class="leistung-teaser">
Some more text
</div>
</section>
<script>
var maxHeight = 0;
window.setInterval(function(){
$('.leistung').each(function(){
var thisH = $(this).height();
if (thisH > maxHeight) { maxHeight = thisH; }
});
$('.leistung').height(maxHeight);
}, 5000);
</script>
Since the OP is looping using each and since there are no any other elements with the class name leistung, I don't think he wants only to take the <section class="leistung"> element. So I assume that he want to select all the elements with name starting leistung.
<script>
var maxHeight = 0;
window.setInterval(function(){
//added ^ selector here
$("[class^=leistung]").each(function(){
var thisH = $(this).height();
if (thisH > maxHeight) { maxHeight = thisH; }
console.log(maxHeight);
});
// and here
$("[class^=leistung]").height(maxHeight);
}, 1000);
</script>
I found my problem. I only run the fuction every 5 seconds. But when the height has been set once it will just fetch the set height again and set it again...
I will have to come up with something else to solve my problem
I am just begginer. I am trying to get font size of the element into variable. After that I would like to set font size of another element using this variable.
I have been looking for the solution for 12 hours and found nothing. I would be grateful for any tips. Thanks in advance.
My code is below.
jQuery(window).scroll(function() {
var OldFont = jQuery('.mhmainnav').find('li').find('a').css("font-size");
var windowTop = jQuery(window).scrollTop();
if (windowTop > 280) {
jQuery('.mh-main-nav').find('li').find('a').css("font-size", "12px");
} else {
jQuery('.mh-main-nav').find('li').find('a').css("font-size", OldFont);
}
});
The only thing I would change is moving the old font to outside your scroll, otherwise when you change the font-size to 12px, OldFont will get overwritten next time you scroll.
Maybe probably cache your anchor selector too for better performance
Also check your mhmainnav selector - you change it to mh-main-nav
var anchors = jQuery('.mhmainnav').find('a'), // if you are reusing this in the scroll, cache it here for better performance
OldFont = anchors.css("font-size"); // set this before the scroll as it shouldn't change once set
jQuery(window).scroll(function() {
var windowTop = jQuery(this).scrollTop();
if (windowTop > 280) {
anchors.css("font-size", "12px");
} else {
anchors.css("font-size", OldFont);
}
});
try this:
$(document).ready(function(){
$(window).scroll(function() {
var OldFont = parseInt($('p').css("font-size"));
alert(OldFont);
});
});
This will alert the font-size, now you cane use it as require.
can you try this following HTML and Jquery snippets
HTML code
<ul class="mhmainav">
<li>
aaa
aaa
aaa
aaa
</li>
</ul>
JQuery
var oldFont= $('.mhmainav li a');
$.each(oldFont, function(index, value){
$(value).css('font-size'); // get font-size value
$(value).css('font-size','20px'); //set font-size value;
});
var size = $(YOUR STYLE PARENT SELECTOR).css('font-size');
Then:-
$(YOUR STYLE Target Selector).css({ 'font-size': size });
Hope this would help you :-)
I have this code:
...<script>
function handleSize()
{
var setObjectSize=window.innerWidth - 600;
document.getElementById("spin").style.width=setObjectSize + "px";
document.getElementById("spin").style.height=setObjectSize + "px";
}
</script>
</head>
<body>
<section id="spin" onLoad="handleSize()">...
All I am trying to do is to create a function that will set the height and width of the element according to window size using a formula and make sure height and width are the same. I am very new to javascript (almost know nothing about it), so despite there being a ton of example of such questions, and me following them, I can't get this code to work. What am I doing wrong?
The problem that I'm seeing, is that the onload event for the section tag isn't firing. You should add your javascript as a self-executing anonymous function to the end of your body tag and this will work for you.
<body>
<section id="spin" style="border:5px solid black;"></section>
<script>
(function () {
var setWindowSize = window.innerWidth - 600;
document.getElementById("spin").style.width = setWindowSize + "px";
document.getElementById("spin").style.height = setWindowSize + "px";
})();
</script>
</body>
See Here for a demo: http://jsfiddle.net/T7DW6/
You should move onload to the body tag:
<body onLoad="handleSize()">
<section id="spin">...
I would suggest you to use jQuery, that is JavaScript library used world wide. So in order to develop it using jQuery you need to do next
function setElementSize(elId) {
var _w $(window); //to get instance of window
var _el $('#' + elId); //jquery to get instance of element
var _width = _w.width();
var _height = _w.height();
//set width=height
if(_height>_width)
{
_height = _width;
} else { _width = _height; }
_el.css({
width: _width,
height: _height
});
}
//this will execute script when document is loaded.
$(document).ready(function(){
setElementSize('spin');
});
Function above will set width and height of element to match window size. If height > width then it will use width as width & height otherwise it will use height.
I assume that you want to change this automatically if window is resized then do this
$(window).resize(function(){
setElementSize('spin');
});
The onload event occurs when an object has been loaded.
onload is most often used within the element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.).
onload is only Supported by the Following HTML Tags:
body, frame, frameset, iframe, img, input type="image", link, script, style
from here: event_onload
then a is may be not the best here (height and weight does not change anything, you should use a div.
In order to know, the one to use, please read this:
what-is-the-difference-between-section-and-div
I try your exam and it works fine. The only thing that i changed was the way that you call the function
function handleSize(){
var setWindowSize=window.innerWidth - 600;
document.getElementById("spin").style.width=setWindowSize + "px";
document.getElementById("spin").style.height=setWindowSize + "px";
}
window.onload = function () {
handleSize();
}
I think that onLoad="handleSize()" have to be onload="handleSize()" but don't use that way because it is not a good practise!
this works for me
<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button and watch it grow.</p>
<button id = "myButton" onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var w = window.innerWidth;
var h = window.innerHeight;
var x = document.getElementById("myButton");
x.style.width = w + "px";
x.style.height = h + "px";
}
</script>
</body>
</html>
here is my code
<div class="entry-content"> <p>some text...</p> <p>some text...</p> <p>some text...</p> </div>
My entry-content div has an absolute positioning, so the text inside the p tags goes under the footer. i have to fix the height of entry-content to total height of all p tags using javascript.
please help.
Use outerHeight (Get the current computed height for the first element in the set of matched elements, including padding, border, and optionally margin.)
var total = 0;
$('.entry-content').find('p').each(function() {
total += $(this).outerHeight(true);
});
$('.entry-content').height(total);
Try like this... Working Demo
var height = 0;
$('div.entry-content p').each(function() {
height += parseInt($(this).outerHeight(true));
});
Have you tried using $('.entry-content').height(), or similar functions like .innerHeight()? (jQuery docs).
You wouldn't need to set the height of the <div>, but you could measure the default height, and use that to position your footer.
A word of warning: because of text wrapping, the height of that div might change when the window is resized. You might want to set a callback using $(window).resize(...), to update the positioning when that happens.
I made a little jQuery plugin a while back that hopefully will come in handy for a problem such as this:
Plugin
(function ($) {
// helper 'plugin' for getting the total height
$.fn.totalHeight = function ()
{
var totalHeight = 0;
this.each(function () {
totalHeight += $(this).height();
});
return totalHeight;
}
})(jQuery);
Usage
var totalHeight = $('.entry-content p').totalHeight();
Edit: This could easily be adapted to support outerHeight() or innerHeight().
jsBin demo
Use: outerHeight(true)
var entryHeight = $('.entry-content').outerHeight(true);
$('#footer').height(entryHeight);
$(function(){
var totaltHeight;
$('.entry-content p').each(function(){
totaltHeight = totaltHeight +$(this).height();
});
});
something like that perhaps
this is depended on jQuery