Change element attribute when window resized (using WordPress) - javascript

I am very new to this and might be a newbie question with a so simple solution, but it is giving me a lot of headache.
I am making a WordPress site. Need to change a header image depending on a window width. Tried so many combinations that I found online, but none of them works. No idea if I should be using JS or Jquery.
This is what I got:
In my "header.php" file i have this:
<img src="<?php echo get_template_directory_uri(); ?>" alt="<?php bloginfo('name'); echo " - "; bloginfo('description');?>" id="logo" />
In my "functions.php" file i have this:
wp_enqueue_script( 'osmpg-logo', get_template_directory_uri() . '/js/logo.js', array(), '20150329', true );
This is the problem. This is my "logo.php" file:
$(document).ready(function($){
$(window).resize(function() {
var logo = $('logo');
logo.attr('src') += '/images/logo.png';
var windowsize = $(document).width();
if ((windowsize) <= 800){
logo.attr('src') = str.replace("logo", "logo1");
}
}
});
I know that the script does execute. I see it when I use debugging tools in browser. It just has no effect on my image. It is always only the result of "get_template_directory_uri();"
What I want is to add '/images/logo.png' for 800+ width, or '/images/logo1.png' for 799+ width, after the result of get_template_directory_uri(); template tag.
EDIT:
Now I have this 'error free' code. Now I need to make it do what I need to do.
jQuery(document).ready(function($){
// cache the element outside rezise handler, so that the DOM isn't searched on every resize:
var $logo = $('#logo');
$(window).resize(function() {
//declare current value of the src attribute:
var $src = $logo.attr('src');
//declare current window size:
var windowsize = $(document).width();
//check current window size and src attribute:
if ((windowsize) >= 800 && $src !== '/images/logo.png'){
//set new src value:
$logo.attr($src, '/images/logo.png');
//check current window size and src attribute again:
}else if((windowsize) < 800 && src !== '/images/logo1.png'){
//set new src value:
$logo.attr($src, '/images/logo1.png');
}
});
// update logo when page is displayed:
$(window).trigger('resize');
});
EDIT 2:
This code works, but only in IE. In Chrome, breaking point is 818px and not 801px. Any ideas? Maybe document.width includes browser scrollbar?
jQuery(document).ready(function($){
var logo = $('#logo');
$(window).resize(function() {
var src = logo.attr('src');
var logo_prefix = src.replace('/images/logo.png', '');
logo_prefix = logo_prefix.replace('/images/logo1.png', '');
var logo0 = logo_prefix + '/images/logo.png';
var logo1 = logo_prefix + '/images/logo1.png';
var windowsize = $(document).width();
if ((windowsize) > 800 && src !== logo0){
logo.attr('src', logo0);
}else if((windowsize) <= 800 && src !== logo1){
logo.attr('src', logo1);
}
});
$(window).trigger('resize');
});

First : $('logo') is not a proper selector. Selecting an element with specific id attribute, you should use # (hash) in front : $('#logo')
Next, jQuery .attr() does accept two arguments:
1 attribute name;
2 attribute value;
With logo.attr('src') you can read the value of src attribute.
To set the attribute, you have to pass the new value in second argument:
logo.attr('src', 'new_logo.png')`
Also, you should always check both conditions (window size and current logo) so that the logo isn't updated unnecessary if current window size and logo still meets conditions.
// cache the element outside rezise handler, so that the DOM isn't searched on every resize:
var logo = $('#logo');
$(window).resize(function() {
//declare current value of the src attribute:
var src = logo.attr('src');
//declare current window size:
var windowsize = $(document).width();
//check current window size and src attribute:
if ((windowsize) >= 800 && src !== '/images/logo.png'){
//set new src value:
logo.attr('src', '/images/logo.png');
//check current window size and src attribute again:
}else if((windowsize) < 800 && src !== '/images/logo1.png'){
//set new src value:
logo.attr('src', '/images/logo1.png');
}
});
// update logo when page is displayed:
$(window).trigger('resize');

See https://api.jquery.com/attr/
Here is wrong expressions logo.attr('src') = str.replace("logo", "logo1"); and logo.attr('src') += '/images/logo.png';. This expressions do nothing, method "attr" with one argument is simple attribute getter.
For setting attribute you must use two arguments, attribute name and value. In your example it some sort of logo.attr('src', "logo1"); and logo.attr('src', '/images/logo.png')
And $('logo'); selector return some list of <logo ... tags, you may need an image 'img' tag or some element with id?

Final code:
jQuery(document).ready(function($){
var logo = $('#logo');
$(window).resize(function() {
var src = logo.attr('src');
var logo_prefix = src.replace('/images/logo.png', '');
logo_prefix = logo_prefix.replace('/images/logo1.png', '');
var logo0 = logo_prefix + '/images/logo.png';
var logo1 = logo_prefix + '/images/logo1.png';
var windowsize = $('.wrapper').width();
if ((windowsize) > 600 && src !== logo0){
logo.attr('src', logo0);
}else if((windowsize) <= 600 && src !== logo1){
logo.attr('src', logo1);
}
});
$(window).trigger('resize');
});
The solution to my first problem (script not working at all) is realizing that JQuery in Wordpress works in a no-conflict mode.
more info
The solution to my last problem (CSS and JQuery calculate width of a document differently) is found here.
Solutions for most other problems provided by #Artur Filipiak. Thank you :)

Related

Bootstrap responsive iframe with auto height calculation

I need to embed link in iFrame contents of the iframe are responsive and i want iframe to auto adjust to the height of iFrame so that whole iframe page is visible.
http://quran.ksu.edu.sa/m.php
Fiddle http://jsfiddle.net/ww09rtbb/3/
I am not sure how to do it so that all content of iframe are visible.
Not sure if there is any build in css property to do it or i have to use jquery for it
UPDATED:
I have somehow managed to do it with jquery
http://jsfiddle.net/ww09rtbb/5/
I am calculating and multiplying width by 1.8
var ifrmw = $('.content-wrapper' ).width();
var iframeh= ifrmw * 1.8;
//alert(iframeh);
$('.iframecls').css('min-height',iframeh);
This can further be improved to to get exact height of iframe
I ran into a similar issue, and I had to write a function that checks for the height of the iframe every 200 milliseconds using setInterval():
function adjustIframeHeight(iframe, minHeight, fix){
var height = 0, $frame = $(iframe);
if(typeof fix=='undefined') fix = 0;
setInterval(function(){
if( typeof $frame.contents()!=null && typeof $frame.contents() !='undefined' && $frame.contents() !=null && $frame.attr('src')!='') {
curHeight = $frame.contents().find('body').height();
$frame.css('height', height + fix); // you might need to add some extra values like +20px.
} else {
$frame.css('height', minHeight); // minimum height for the iframe.
}
},200);
}
Then call it like this:
$(function(){
adjustIframeHeight('#iframeID', 200, 0);
});

Dynamically Changing Class on Window Resize

What I'm doing and have spent many hours attempting today is add a class to an element when the window is resized using the value of the viewport.
Basically, I want to add the class as the viewport value in <html> on page load, then change that class as it is resized.
Page load - add value of viewport as a class to <html>
Window resize - change the class added to <html> as the viewport value
Right now I have the first part down and I have the second almost there. It will add the viewport value as a class, then when resized add the new value - but it is just adding never ending new classes and not swapping them out.
Modified code
omitted var $html = $("html");
if(typeof window.innerWidth!='undefined'){
viewportwidth=window.innerWidth
}
jQuery(window).resize(function(){
var viewportwidth;
if(typeof window.innerWidth!='undefined'){
viewportwidth=window.innerWidth;
}
jQuery("html").toggleClass(""+viewportwidth);
});
jQuery("html").addClass(""+viewportwidth);
I'm not very experienced with jQuery and JS...
Example - http://sandbox.iemajen.com/
Thanks.
Your question has been identified as a possible duplicate of another question.
Let me try to explain more clearly. I would like to have the current value of window.innerWidth returned as the only class. That is, when the window is resized, the class cycles to the next value replacing the former.
Screenshot
Try this Answer
//OnLoad:
$(document).ready(function(){
w_w = $(window).width();
if(w_w > some_value){
$("#some_id").addClass('someClass');
}
//onResize
$(window).resize(function(){
w_w = $(window).width();
if(w_w > some_value){
$("#some_id").addClass('someClass');
}
});
});
Maybe you can try something like this :
jQuery(window).resize(function(){
var viewportwidth;
if(typeof window.innerWidth!='undefined'){
viewportwidth=window.innerWidth;
}
if(viewportwidth >= 768){
$html.addClass("res_768");
}else{
$html.removeClass("res_768");
}
if(viewportwidth >= 640){
$html.addClass("res_640");
}else{
$html.removeClass("res_640");
}
//etc...
});
or
jQuery(window).resize(function(){
var viewportwidth;
if(typeof window.innerWidth!='undefined'){
viewportwidth=window.innerWidth;
}
$html.removeClass();//remove all classes
if(viewportwidth >= 768){
$html.addClass("res_768");
}
else if(viewportwidth >= 640){
$html.addClass("res_640");
}
//etc...
});

Resize iframe to content with Jquery

I'm trying to resize an iframe dynamicly to fit its content. To do so I have a piece of code:
$("#IframeId").height($("#IframeId").contents().find("html").height());​
It doesnt work. Is it because of cross-domain issue? How do I get it to fit? Please take a look at Fiddle: JsFiddle
ps I have set the html and body of the link height:100%;
You just need to apply your code on the iframe load event, so the height is already known at that time, code follows:
$("#IframeId").load(function() {
$(this).height( $(this).contents().find("body").height() );
});
See working demo . This demo works on jsfiddle as I've set the iframe url to a url in the same domain as the jsfiddle result iframe, that is, the fiddle.jshell.net domain.
UPDATE:
#Youss:
It seems your page for a strange reason don't get the body height right, so try using the height of the main elements instead, like this:
$(document).ready(function() {
$("#IframeId").load(function() {
var h = $(this).contents().find("ul.jq-text").height();
h += $(this).contents().find("#form1").height();
$(this).height( h );
});
});
Not sure why #Nelson's solution wasn't working in Firefox 26 (Ubuntu), but the following Javascript-jQuery solution seems to work in Chromium and Firefox.
/**
* Called to resize a given iframe.
*
* #param frame The iframe to resize.
*/
function resize( frame ) {
var b = frame.contentWindow.document.body || frame.contentDocument.body,
cHeight = $(b).height();
if( frame.oHeight !== cHeight ) {
$(frame).height( 0 );
frame.style.height = 0;
$(frame).height( cHeight );
frame.style.height = cHeight + "px";
frame.oHeight = cHeight;
}
// Call again to check whether the content height has changed.
setTimeout( function() { resize( frame ); }, 250 );
}
/**
* Resizes all the iframe objects on the current page. This is called when
* the page is loaded. For some reason using jQuery to trigger on loading
* the iframe does not work in Firefox 26.
*/
window.onload = function() {
var frame,
frames = document.getElementsByTagName( 'iframe' ),
i = frames.length - 1;
while( i >= 0 ) {
frame = frames[i];
frame.onload = resize( frame );
i -= 1;
}
};
This continually resizes all iframes on a given page.
Tested with jQuery 1.10.2.
Using $('iframe').on( 'load', ... would only work intermittently. Note that the size must initially be set to 0 pixels in height if it is to shrink below the default iframe height in some browsers.
What you can do is the following:
Within the iFrame use document.parent.setHeight(myheight) to set the height within the iFrame to the parent. Which is allowed since it is a child control. Call a function from the parent.
Within the parent you make a function setHeight(iframeheight) which resizes the iFrame.
Also see:
How do I implement Cross Domain URL Access from an Iframe using Javascript?
Just do it on the HTML tag, works perfect
$("#iframe").load(function() {
$(this).height( $(this).contents().find("html").height() );
});
As the answer to the question use an already outdated jquery (load has been deprecated and replaced with .on('load',function(){}), below is the latest code for the answer in the question.
Note that I use the scrollHeight and scrollWidth, which I think will load much nicer than using Height and Width like the answer provided. It will totally fit, without scroll anymore.
$("#dreport_frame").on('load',function(){
var h = $('#dreport_frame').contents().find("body").prop('scrollHeight');
var w = $('#dreport_frame').contents().find("body").prop('scrollWidth');
$('#dreport_frame').height(h);
$('#dreport_frame').width(w);
})
Adjust height of an iframe, on load and resize, based on its body height.
var iFrameID = document.getElementById('iframe2');
var iframeWin = iFrameID.contentWindow;
var eventList = ["load", "resize"];
for(event of eventList) {
iframeWin.addEventListener(event, function(){
if(iFrameID) {
var h = iframeWin.document.body.offsetHeight + "px";
if(iFrameID.height == h) {
return false;
}
iFrameID.height = "";
iFrameID.height = iframeWin.document.body.offsetHeight + "px";
}
})
}
At end, I come with this cross-domain solution that work also for resize...
(resize not triggering : Auto resize iframe height when the height of the iframe contents change (same domain) )
Iframe :
(function() {
"use strict";
var oldIframeHeight = 0,
currentHeight = 0;
function doSize() {
currentHeight = document.body.offsetHeight || document.body.scrollHeight;
if (currentHeight !== oldIframeHeight) {
console.log('currentHeight', currentHeight);
window.parent.postMessage({height:currentHeight}, "*");
oldIframeHeight = currentHeight;
}
}
if (window.parent) {
//window.addEventListener('load', doSize);
//window.addEventListener('resize', doSize);
window.setInterval(doSize, 100); // Dispatch resize ! without bug
}
})();
Parent page :
window.addEventListener('message', event => {
if (event.origin.startsWith('https://mysite.fr') && event.data && event.data.height) {
console.log('event.data.height', event.data.height);
jQuery('#frameId').height(event.data.height + 12);
}
});

How to change the height of div with the content of other div

I have two div in my website page one beside the other(one left and one right),I want to change the height of the left one with the content of the right one using javascript
I tried to have the dynamic height of the right div :
function getHeight() {
var doc = document.getElementById('div.right');
if (document.all) // ok I.E
{
H = doc.currentStyle.height;
}
else // ok FF
{
H = document.defaultView.getComputedStyle(doc, null).height;
}
}​
But I stopped here because I don't know how to pass the javascript variable to my page of style CSS,I mean I dont know how to apply this value in the other div(left div) in the same page automatically.
Any Idea?
Just use
document.getElementById('div.left').style.height = H;
Edit
AFAIK you cant modify an external stylesheet from javascript
Is the height of the div determined at the time the document is served, loaded or or any arbitrary time after the document has loaded?
The code I suggested above was to be used like this(I'm assuming your IE code is correct)
function getHeight() {
var doc = document.getElementById('div.right');
if (document.all) // ok I.E
{
H = doc.currentStyle.height;
}
else // ok FF
{
H = document.defaultView.getComputedStyle(doc, null).height;
}
document.getElementById('div.left').style.height = H;//✔
}
Just to help people I found a great code to change the height of two div autoamtically using a little of Jquery :
<script type='text/javascript'>
$(window).load(function(){
var lh = $('#div.right').height();
var rh = $('#div.left').height();
if (lh >= rh){
//alert('left : ' + lh);
$('#div.left').height(lh);
} else {
//alert('right : ' + rh);
$('#div.right').height(rh);
};
});
</script>
It's works for all navigators.

Adding CSS Class According to Image Ratio

I'm creating an image gallery with dozens of landscape and portrait images on a single page. I want to style each image with a dynamically added CSS class (i.e. ".landscape" for landscape images) according to its orientation.
I came across the code below (from 2003!) For determining the ratio and adding a class for a single image, but I need the classes to be added automatically for all images within a certain div id. Honestly, I just don't know enough about JavaScript or jQuery to solve this on my own.
<script language="JavaScript" type="text/javascript">
<!--
function getDim() {
myImage = new Image;
myImage.src="myimage.gif";//path to image
document.divImage.src=myImage.src;
var imgProp;
var width = myImage.width;
var height = myImage.height;
var ratio = width/height;
if ( ratio > 1 ) {
document.getElementById('image').className="portrait";
}
else {
document.getElementById('image').className="landscape";
}
}
//-->
</script>
with jQuery:
$('#divID img').each(function(){
$(this).addClass(this.width > this.height ? 'landscape' : 'portrait');
});
Pretty straightforward jQuery:
$('#yourId').find('img').each(function(i,elem){
var $this = $(this),
ratio = $this.width() / $this.height();
$this.addClass((ratio < 1) ? 'portrait' : 'landscape');
});
See example →
Lets say, that your containing div is of class gallery and you are using jQuery :)
$(document).ready(function(){
$('.gallery img').each(function(){
var width = $(this).width();
var height = $(this).height();
var className;
if (width/height > 1) className = "portrait";
else className = "landscape";
$(this).addClass(className);
});
});
This way is longer, but allows you to add more rules (if there is any reason to do so :).. ie.:
if (width/height == 1) className = "square";
If setting img width/height interferes with your css, you can set it as data-width/data-height:
$('#your-div-Id').find('img').each(function(i,elem){
var $this = $(this),
ratio = $this.attr('data-width') / $this.attr('data-height');
$this.addClass((ratio < 1) ? 'portrait' : 'landscape');
});
HTML:
<div id="your-div-Id">
<img src="#" data-width="60" data-height="30" />
</div>
Edited mVChr's example

Categories

Resources