If...Else: If iFrame exists, apply CSS to page? - javascript

I'm new here. And very new to programming, markup, web dev. I do have some basic understanding of HTML and CSS, but this is my first attempt at using jQuery/Javascript.
Is it possible to use jQuery (or otherwise) to
1- detect if an iframe with class="iframe1" appears on a given page and
2- if it does exist, to remove the primary navigation bar with id="main-header" ?
I'm currently using this custom CSS to hide the navigation globally:
#main-header {
display:none !important;
}
and then using this (for example) to replace it on individual pages:
.page-id-1350 #main-header {
display:block !important;
}
Obviously this is not ideal, and I very much like to automate this process.
Thanks very much in advance,
Chris

You can use the following jQuery code to do just that:
if($(".iframe1").length > 0) // If .iframe1 exists
$("#main-header").hide(); // Hide #main-header
Or, go the opposite way, keep your CSS that hides #main-header and then show it when .frame1 is not present on the page:
if($(".iframe1").length == 0) // If .iframe1 does not exists
$("#main-header").show(); // Show #main-header

You could do this with JavaScript, with code like this:
<script>
// Place this at the end of the body
window.addEventListener("load", function(){
var iframeTest = document.querySelectorAll("iframe.iframe1");
var navBar = document.getElementById("main-header");
if (iframeTest.length > 0) {
navBar.setAttribute("style","display:none");
}
});
</script>

Related

An AJAX Search Plugin is removing my Event Listeners from an 'Accordion' style list

I'm using Search & Filter pro WP plugin for the ease of a client using it.
I've created a results page and filter on a demo site (for testing) that works fine but I know the categories will get large on the real site. So I turned the plugins' filters into an Accordion style list.
It works fine until certain searches reload all those filter results with AJAX and they remove my event listeners (which are sitting on elements for the moment, I know it's not ideal but for now I just want to see if it could work).
I imagine because my script has already been parsed when the DOM loaded, the AJAX from the plugin is just redefining those elements and they are then missing the Event Listeners or something.
Any help would be appreciated.
Here's my script:
<?php
add_action( 'wp_footer', function () { ?>
<script>
const clicker = document.querySelectorAll('#search-filter-form-4346 > ul > li > h4');
// looping through the <h4> elements and adding an event listener onto each, the class toggle just adds an animation to a pseudo-element spinner
for (let i = 0; i < clicker.length; i++) {
clicker[i].addEventListener("click", function() {
this.classList.toggle("open-filter-dropdown");
console.log('EL was created');
// declaring the <ul> as a variable
const openFilterPanel = this.nextElementSibling;
// animating the <ul> elements max-height
if (openFilterPanel.style.maxHeight) {
openFilterPanel.style.maxHeight = null;
} else {
openFilterPanel.style.maxHeight = openFilterPanel.scrollHeight + "px";
}
console.log('openFilterPanel style is changed');
});
}
</script>
<?php } );
I'm pretty new to javascript, I get the basic concepts but this kind of an interference is above my head. I tried refactoring my code, forcing the page to refresh and other such measures. None of these work very well. I also thought I could use a 'loadend' event on the document to re-add my ELs but that didn't work either.
Hoping there is a workaround here, otherwise I might have to find another solution or plugin.
Thanks in advance!

div onclick function to change body background image

I want a small picture that acts like a button, to be click-able with a function to change the body background-image. I am a total newbie and I'm trying to learn. The most simple way, I thought, would be to have a div with a background-image.
I have to use unsemantic grid, also.
So I pretty much only have the div with a background image. How do I write this function? I'm sure it's really easy and I've read like 20 threads here but none of them were useful for me
Edit: added my code
#knapp {
height:50px;
width:50px;
background-image:url(http://ingridwu.dmmdmcfatter.com/wp-content/uploads/2015/01/placeholder.png);
background-repeat:no-repeat;
background-size:contain;
position:absolute;
top:90vh;
right:3vw;
}
<div id="knapp" class="grid-10 prefix-90"></div>
Add cursor on the div to appear clickable
#knapp {
cursor: pointer;
}
You could put the new background-image in a new css rule
body.newbg {
background-image:url(path-to-new-background.png);
}
This is body with the old background-image
body {
background-image:url(path-to-old-background.png);
}
and with jquery just add/toggle the class by doing something like that (in $(document).ready()):
$('#knapp').on('click', function(){
$('body').addClass('newbg');
// you could instead do toggleClass if you want for each click to have background switch between old background and new background
});
This is a cleaner approach compared to all the other answers as it separates presentation (css), structure (html) and behavior (javascript).
This is because it doesn't use JavaScript to change style directly. Also it doesn't pollute html with onclick which is also a bad practice.
Here is a plunkr: https://plnkr.co/edit/aiGZmvvi6WWGFs7E9xTp
and here is one with a circular collection of backgrounds (thanks to Kai's idea)
https://plnkr.co/edit/0djmmNM9OOTdfYyvLvUH?p=preview
Create a button with onclick attribute with a function name like replace.
Defined the function in your script like:
function replace() {
document.body.style.backgroundImage = 'url(https://lh6.ggpht.com/8mgTDZXaLMS1JsnF28Tjh6dahHwN1FqcXCVnifkfppmNLqnD-mPBuf9C1sEWhlEbA4s=w300)';
}
Explanation:
You set the style property of the body (using document.body object) to other background-image.
If something is not clear, I will happy to explain.
Working example:
function replace() {
document.body.style.backgroundImage = 'url(https://lh6.ggpht.com/8mgTDZXaLMS1JsnF28Tjh6dahHwN1FqcXCVnifkfppmNLqnD-mPBuf9C1sEWhlEbA4s=w300)';
}
body {
background-image: url(http://www.julienlevesque.net/preview/google-smile-preview.jpg);
}
div {
background:blue;
color:#fff;
float:left;
}
<div onclick="replace()">Replace background-image</div>
This may help you...
$('.yourClassofDiv').click({
$(this).css("background-image",'url("' + URLofIMAGE+ '")')
});
Try using onclick at div#knapp element , set document.body.style.background to url of image file
#knapp {
height:50px;
width:50px;
background-image:url(http://lorempixel.com/50/50);
background-repeat:no-repeat;
background-size:contain;
position:absolute;
top:90vh;
right:3vw;
}
<div id="knapp" class="grid-10 prefix-90" onclick="document.body.style.background = 'url(http://lorempixel.com/'+ window.innerWidth + '/'+ window.innerHeight +') no-repeat'"></div>
here is a simple way in jquery
$(document).ready(function() {
$("body").css('background-image', 'url(http://julienlevesque.net/Requiem/images/detail-requiem.jpg)').css('background-repeat', 'no-repeat');
$('div').css('cursor', 'pointer').click(function() {
$("body").css('background-image', 'url(http://julienlevesque.net/Requiem/images/Requiem-Julien-Levesque.jpg)');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<body>
<div style="background-color:yellow">Click Here to change background Image</div>
</body>
Here i will explain the code.
The jQuery syntax is tailor made for selecting HTML elements and performing some action on the element(s).
Basic syntax is: $(selector).action()
A $ sign to define/access jQuery
A (selector) to "query (or find)" HTML elements
A jQuery action() to be performed on the element(s)
$(this).hide() - hides the current element.
$("p").hide() - hides all <p> elements.
$(".test").hide() - hides all elements with class="test".
$("#test").hide() - hides the element with id="test".
Here is what happen in the code.
1.
$(document).ready(function(){
// jQuery methods go here...
});
This is to prevent any jQuery code from running before the document is finished loading (is ready).It is good practice to wait for the document to be fully loaded and ready before working with it. This also allows you to have your JavaScript code before the body of your document, in the head section.
2
$("body").css('background-image', 'url(http://julienlevesque.net/Requiem/images/detail-requiem.jpg)').css('background-repeat', 'no-repeat');
getting the body element of your html and set its background-image with .css() action. which i gave it more one action
3
$('div').css('cursor', 'pointer').click(function() {
$("body").css('background-image', 'url(http://julienlevesque.net/Requiem/images/Requiem-Julien-Levesque.jpg)');
});
this is where the change takes place. i got the div to be clicked by $('div') and first gave it an action of changing the mouse to cursor to indicate its clickable and then gave it the click function, where our background-image get changed on click
If I understand the question, you should be able to create a variable in jQuery which is an array of all the string versions of your image urls that you want to use:
var images = ['../images/####','../images/$$$$', 'http://some.other/url.here];
// do this for as many images as you want to cycle through
Like that.
Then you can make a counter variable:
var counter = 0;
and set it to zero.
Next, add the event listener on() to your div like this:
$('#knapp').on('click', function(){
});
Finally, inside your event listener, change the CSS background-image property of the div to one of your images in the array:
// do this inside a document.ready() function
$('#knapp').on('click', function(){
$(this).css('background-image','url("' + images[counter] + '")');
counter++;
});
I hope this helped! Also, remember to increment counter
EDIT ----------------------------------------------------------------
OK, so I totally jumped over something obvious which is the fact that the counter might go too high and access something out of scope. To prevent this add the following inside of your on() listener:
if(counter >= images.length - 1){
counter = 0;
}
EDIT 2 --------------------------------------------------------------
Ok, so I didn't know what exactly you were asking at first, so here is my second answer. Since it seems like what you are actually trying to do is only switch the background image once on click, then you could use something like this:
$(document).ready(function(){
$('#knapp').on('click', function(){
$(this).css('background-image','url("YOUR_NEW_URL_HERE")');
});
});
or you could have it toggle between two images by making two identical classes in CSS (except for the background image) and replacing one with the other using .addClass and .removeClass.
EDIT 3---------------------------------------------------------------
I never thought I would edit this post this many times, but apparently I missed that the body background image should be changed (thanks to comments). My bad and thanks for pointing it out (even if you were talking to someone else).

Button to toggle all divs of certain class (pure javascript, or loading after jquery)?

I'm trying to insert a toggle button into a wordpress page that will change the state of all divs of class "foo".
Is there either a pure javascript way to do this, or some way of guaranteeing the js will load after the jquery.js loads? I don't really want to deal with trying to figure out how wordpress loads javascript and enqueuing files in the proper order or whatever, this should be 3 lines of javascript that is only needed on this one page.
My HTML / javascript knowledge is minimal, so please include the full code needed.
More details:
There is jquery in my theme, however if I try to use the $(".CLASSNAME").toggle() syntax, I get
"Uncaught TypeError: undefined is not a function"
Which I assume is something to do with my "page" javascript being loaded before jquery is loaded.
I tried various things, like
CSS
.excerpt{
style="display: none"
}
HTML
<input type="submit" value="Show/Hide Excerpts" onclick="toggleDiv();"></input>
<div class="excerpt">text i want to toggle</div>
Javascript, inside "script" HTML tag
$(document).ready(function toggleDiv() {
$(".excerpt").toggle();
} )
This results in the aforementioned "Uncaught TypeError: undefined is not a function"
This looks promising, but I'm not quite sure how to tweak it to toggle / be linked to a button:
https://stackoverflow.com/a/5836870/851192
For the gory details,
This is Wordpress 4.0.1, TwentyFourteen Theme, on a page created with the W4 Post List plugin.
I've been at this for three hours :/ Sigh.
This should work for you (I modified this a bit: https://stackoverflow.com/a/5836870/851192):
Javascript:
function toggleDiv() {
var divs = document.getElementsByTagName('div');
var toggle = function() {
for (var i = 0, l = divs.length; i < l; i++) {
if (divs[i].getAttribute('class') == 'excerpt')
if (divs[i].style.display == 'none') divs[i].style.display = '';
else divs[i].style.display = 'none';
}
}
}
HTML:
<input type="submit" value="Show/Hide Excerpts" onclick="toggleDiv();"></input>
...
<div class="excerpt">...</div>
Note that you do not need the class excerpt defined in CSS at all.
All the Javascript code needs is that all the divs you want toggled are marked with this class:
if (divs[i].getAttribute('class') == 'excerpt')
If the div is of class excerpt, then this toggles the display style:
if (divs[i].style.display == 'none') divs[i].style.display = '';
else divs[i].style.display = 'none';
Probably, it is due to WordPress loads in "no conflict" mode.
http://codex.wordpress.org/Function_Reference/wp_enqueue_script#jQuery_noConflict_wrappers
jQuery noConflict wrappers
Note: The jQuery library included with WordPress loads in "no conflict" mode. This is to prevent compatibility problems with other javascript libraries that WordPress can load.
In "no-confict" mode, the $ shortcut is not available and the longer jQuery is used. For example:
$(document).ready(function(){
$(#somefunction) ...
});
Becomes:
jQuery(document).ready(function(){
jQuery(#somefunction) ...
});
SOLUTION
Use jQuery instead of $.
function toggleDiv(){
jQuery('.excerpt').toggle();
}
Include your jQuery reference first then include your jQuery code in an IIFE (Immediately Invoke Function Expression) like this:
<script src='jquery/location'></script>
<script src='myscript/location'></script>
The IIFE should look like this:
(function($){
$('.excerpt').toggle();
})(jQuery)
Both of these script tags should be the last tags before your closing </body> tag. This way your content is loaded and the use does not have to wait for your scripts to load before he/she sees the content. If you need the elements hidden on load (i.e. you try it and the elements are visible when the page load and then are hidden) then you should apply a CSS style and use jQuery's toggleClass() method to hide/show or apply display:none; directly to the element and use toggle() when you want to show the item.
.hidden{
display:none;
}
The other problem you are going to have is your input type is submit which with trigger a POST (or GET). This does not look like what you want to do so you should use a button tag with the type=button.
Bind an click event in jQuery:
$('#toggle').on('click', function(){
$('.excerpt').toggleClass('hidden');
});
Here a Fiddle: http://jsfiddle.net/24xfa0sL/1/
I haven't dug through the responses yet, thanks for all of them. upvotes for everyone on the mythical day I get 15 points. Sorry for my not-perfectly-edited question, I was ready to go to sleep at that point.
I ended up figuring it out based on this jsfiddle:
http://jsfiddle.net/robert/PkHYf/
HTML
<button id="Toggle">Show/Hide Excerpts</button>
[...stuff...]
<div class="excerpt" style="display:none;">
<ul style="margin:0 0 5px 20px;">[excerpt wordlimit=20] </ul></div>
JS
var divs = document.getElementsByTagName('div');
var toggle = function() {
for (var i = 0, l = divs.length; i < l; i++) {
if (divs[i].getAttribute('class') == 'excerpt')
if (divs[i].style.display == 'none') divs[i].style.display = '';
else divs[i].style.display = 'none';
}
}
document.getElementById('Toggle').onclick = toggle;
picture of before/after button clicking to clarify desired behavior

Javascript display html if div exists

I am trying to display a table (or ul) that will contain a navigation bar on my page, but only displays the tabs that will contain jquery called divs present on the html.
Essentially, it's a single html document that contains all divs, jquery hides all divs but the first, and the nav bar will allow to navigate through each.
Now I am trying to make it easy to use for my client, so that the menu items will only exist if the div for it also exists. I've got most of it done, the only thing is actually knowing if a div exists.
I tried using this:
if(document.getElementById("page1")) {
document.write("<b>Good morning</b>");}
else
{
document.write("<b>Bad morning </b>");
}
When I place the above code within the div page1, it returns true. Is there no way to do it from the top of the page and not within the div?
Thanks!
Update:
As suggested by many, I have used the following:
$j(document).ready(function(){
//Hide the sections we don't need right away
$j("#page2").hide();
$j("#page3").hide();
$j("#page4").hide();
if ($j('#page1').length > 0) {
var page = 'Excellent Morning' ;
}
});
Then when I try to use:
document.write(page);
It displays the following instead:
[object HTMLBodyElement]
Why not use jQuery since you are already?
if ($('#page1').length > 0) {
// do stuff...
}
EDIT: As davin pointed out, your code should be evaluated after the DOM has been rendered. You can do this by placing it in a $(document).ready call:
$(document.ready(function() {
if ($('#page1').length > 0) {
// do stuff...
}
});
EDIT 2: Based on the OP's edits, a better solution would be to add a placeholder element and to set its content (like FishBasketGordo suggested). An example of this:
$(document.ready(function() {
//Hide the sections we don't need right away
$("#page2, #page3, #page4").hide();
if ($('#page1').length) {
$('#myPlaceHolder').html('<b>Good Morning</b>');
}
else
{
$('#myPlaceHolder').html('<b>Bad Morning</b>');
}
});
Somewhere else in the document...
<span id="myPlaceHolder"></span>
If you place it at the top of the page, the page1 div doesn't exist when the code runs. If you are using jQuery, place the code in a $(document).ready event. Then, you can put it where you want it within the markup. Here's an example:
$(document).ready(function() {
if (document.getElementById("page1")) {
document.write("<b>Good morning</b>");
} else {
document.write("<b>Bad morning </b>");
}
});
Although, rather than doing a document.write, I would consider having a placeholder span or div, and setting it's innerHTML property (or use jQuery's html method). I would also use CSS for my style instead of <b> tags, but that's another matter entirely.
You can use
if ($(selector).length > 0) {
// element exists
}
or you can check out this post for a more elegant solution
Is there an "exists" function for jQuery?

Google related bar - how to keep from showing up on my website

A new "google related" bar shows up at the bottom of my website. It displays links to my competitors and other things like maps, etc. It is tied in with users using the google toolbar. If anyone has any ideas on how I can disable from displaying on my web side I would sure appreciate it.
Taken from http://harrybailey.com/2011/08/hide-google-related-bar-on-your-website-with-css/
Google inserts an iframe into your html with the class .grelated-iframe
So hiding it is as simple as including the following css:
iframe.grelated-iframe {
display: none;
}
Google removed div and frame names and put everything to important so original answer no longer works on my site. We need to wait for the iframe to be created and then hide it by classname. Couldn't get .delay to work, but this does...today anyway.
$(document).ready(function() {
setTimeout(function(){
$(‘.notranslate’).hide();},1000);
});
Following javascript code tries to find the google related iframe as soon as the window finishes loading. If found, it is made hidden, else an interval of one second is initialized, which checks for the specified iframe and makes it hidden as soon as it is found on page.
$(window).load(function (){
var giframe = null;
var giframecnt = 0;
var giframetmr = -1;
giframe = $("body > iframe.notranslate")[0];
if(giframe != null)
$(giframe).css("display", "none");
else
giframetmr = setInterval(function(){
giframe = $("body > iframe.notranslate")[0];
if(giframe != null) {
clearInterval(giframetmr);
$(giframe).css("display", "none");
} else if(giframecnt >= 20)
clearInterval(giframetmr);
else
giframecnt++;
}, 1000);});
Find the parent DIV element that contains the stuff in the bar. If it has an id or name attribute, and you can control the page CSS then simply add a rule for the element, i.e. if you see something like
<div id="footer-bar-div".....
then add a CSS rule
#footer-bar-div {display:none ! important}
This will not work if the bar is inside an iframe element, but even in that case you should be able to hide it using javascript, but you will need to find the name/id of the frame, i.e.:
var badFrame = document.getElementById('badFrameId').contentWindow;
badFrame.getElementById('footer-bar-div').style.display='none';
if the frame has a name, then instead you should access it with:
var badFrame = window.frames['badFrameName']
There is also a chance that the bar is generated on-the-fly using javascript. If it is added to the end of the page you can simply add a <noscript> tag at the end of your content - this will prevent the javascript from executing. This is an old trick so it might not always work.

Categories