I have a need to add a class to certain pages - ones that contain an ID of #hero. For all other pages, the class must not be added.
Because I'm using asp.net with a few layered master pages, its not as simple as just adding a class directly to the html becuase the body tag sits a couple of pages above the aspx page.
I could locate the body tag, but so far I've tried to avoid that due to the added complexity, and instead tried to use jquery.
Here's the code:
$(document).ready(function () {
updateBodyClasses();
});
function updateBodyClasses() {
if($("#hero")) {
$("html, body").addClass("hero");
}
}
Nothing complicated, but here's the rub. By the time the class has been appended, the page has been rendered and the class doesn't seem to have any effect. However, if I test it by adding the class directly to the html, it works - so I know the CSS works and that its a timing issue.
I suppose I could add the code higher up the page - jquery is deferred, so I would need to know the equivalent javascript to try it out.
Would appreciate any thoughts on this potential solution, or perhaps and other ideas.
/* UPDATE */
For clarity, it seems to be the HTML related class that isn't being applied.
You can alter the DOM without waiting for it to be ready.
You need to:
load jQuery in a synchronous way(without defer or async).
Put #hero element i above the script.
Please consider this example:
.red {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="hero">I don't care about DOM being ready</div>
<script>
var $el = $('#hero');
if ($el.length) {
$el.addClass('red');
}
</script>
You can use IIFE(Immidiately Invocked Function Expression):
like:
(function()
{
if($("#hero")) {
$("html, body").addClass("hero");
}
})();
just put your function in document ready like
$(function(){
if($("#hero")) {
$("html, body").addClass("hero");
}
});
No real solution provided.
Not reasitic to change the whole site infrastructure - from one that defers jquery to loading it synchronously.
The two other jquery answers are as per the current setup and don't work.
The only working solution was provided by Tushar, although it would still require selective loading of the script, which was not included in the answer.
In the end, I used a workaround, which bypassed the need for any javascript. Instead of selectively adding a class to html tag, I added the css permanently to the html tag, affecting all pages. I then added an inner div, which reverses it out. This means that any page can now manipulate its own functionality directly without having to add classes to the html tag.
Related
I have a simple jquery script that changes the url path of the images. The only problem is the doesn't apply after I click the load more button. So I'm trying to do a workaround where it calls the script again after clicking the button.
<script type='text/javascript'>
$(document).ready(function ReplaceImage() {
$(".galleryItem img").each(function() {
$(this).attr("src", function(a, b) {
return b.replace("s72-c", "s300")
})
})
});
</script>
HTML
Load More
While Keith's answer will get you what you are looking for, I really can't recommend that approach. You are much better off with something like this.
<script type="text/javascript">
$(function() {
var replaceImage = function() {
$('.galleryItem img').each(function() {
$(this).attr('src', function(index, value) {
return value.replace('s72-c', 's300');
});
});
};
replaceImage();
$('.js-replace-image').on('click', replaceImage);
});
</script>
Using this html
<button class="js-replace-image">Load More</button>
By taking this approach, you do not expose any global variables onto the window object, which can be a point of issue if you work with other libraries (or developers) that don't manage their globals well.
Also, by moving to a class name and binding an event handler to the DOM node via JavaScript, you future proof yourself much more. Also allows yourself to easily add this functionality to more buttons very easily but just adding a class to it.
I updated the anchor tag to a button because of the semantics of what you need to do - it doesn't link out anywhere, it's just dynamic functionality on the page. This is what buttons are best served for.
I'd also recommend putting this in the footer of your site, because then, depending on your situation, you will already have the images updated properly without having to click the button. The only need for the button would be if you are dynamically inserting more images on the page after load, or if this script was in the head of your document (meaning jQuery couldn't know about the images yet).
I hope this helps, reach out if you have questions.
I have a button which acts as a 'copy url' button. This works fine on none mobile devices, however I believe you can't have such a function on mobile devices as they rely on flash. On most mobile sites users must manually copy URLs.
So, I want to remove my 'copy url' button once a mobile device has been detected.
Before you grill me, yes I've read:
Hiding DIV if using mobile browser
I tried the solution mentioned in that thread, however it does not work. Any idea why? Here is my codepen:
http://codepen.io/rjtkoh/pen/dPxKeg
<head>
<script>
var mobile = (/iphone|ipod|android|blackberry|mini|windows\sce|palm/i.test(navigator.userAgent.toLowerCase()));
$('.test').css('display', 'none');
</script>
</head>
<div class= "test">yo test me</div>
Much appreciated.
It doesn't look like you're doing anything with the mobile variable. But before you can get any further, you have to address the issue that is preventing your $('.test').css('display', 'none'); from hiding the div:
The DOM element you are referencing does not exist at the time the script is executed. The script should be executed after the DOM element is created, which can be accomplished a couple of ways:
Move the <script> tag to after the element in the HTML. This assumes that the link to jQuery is somewhere before the script, not after.
Use jQuery's document.ready() function to execute the JavaScript only after the DOM is ready. Since you're already using jQuery, this is usually the most convenient way to do it.
E.g.:
<script>
$(document).ready(function() {
var mobile = (/iphone|ipod|android|blackberry|mini|windows\sce|palm/i.test(navigator.userAgent.toLowerCase()));
$('.test').css('display', 'none');
});
</script>
The reason you're seeing this is because the DOM isn't fully built, so when you're trying to access it using $('.test'), it can't get it. You have to wait until it is fully ready.
Wrap your Javascript code in the ready function provided by jQuery:
$(document).ready(function () {
// your code goes here
});
This code will only be executed once all the DOM has been loaded.
Have a look at the documentation.
A simple way to do this is just add class to the html element when match some situation.
And use a selector to hide the elements you want you hide only when the class exist
This allows you to hide element even the <body></body> haven't actully loaded.
Besides, it requires minimal DOM operation.
So it won't lag the page when there are too many elements needed to hide.
Just put the codes in the <head></head>
<script>
if (navigator.userAgent.search("Some thing") >= 0 ) {
/*the html element*/
var root = document.documentElement;
root.setAttribute( "class", "hide-for-compitibility" );
}
</script>
<style>
html.hide-for-compitibility .selectors{
display : none;
}
</style>
Does anyone look at his codepen? Hey guy,
you did not include Jquery while using it. Put this in your HTML section <script src="https://code.jquery.com/jquery-2.1.3.min.js" type="text/javascript"></script>
you put your script in wrong section, move it to JS section.
the mobile variable you obtained should be used in an IF statement. Example,
if (mobile)
$('.test').css('display', 'none');
else
$('.test').html('This ELSE leg should be removed');
Finally, getting the opinion of other answers that you should wrap your code inside a $(document).ready() function.
Here is an example and it do work. http://codepen.io/anon/pen/QweBgq
Another way that does not use Javascript is that you use CSS. Try below code in CSS section.
.test {
display: none;
}
#media (min-width: 768px) {
.test{
width: 200px;
height: 50px;
background: red;
display: block;
}
}
I'm working to use custom checkbox styles with a checkbox which is dynamically generated by javascript for the Google Identity Toolkit. For example, we add this div:
<div id="gitkitWidgetDiv"></div>
And the Google Identity Toolkit script generates new html for that div.
I need to add a class to the HTML which is added by the javascript without any action by the user and I'm struggling to make it work. For example, here is my code:
$("#gitkitWidgetDiv").on('ready', ".gitkit-sign-in-options label", function() {
$(this).addClass('checkbox');
});
I've tried switching 'ready' for a few other options and also using the livequery plugin, but nothing is working for me. It works if I use an active event like 'click,' but I can't figure out how to do this when the page loads. Could someone please help? Thanks!
Modern browsers (including IE11) support mutation obervers. You can use one to monitor the parent node of the div that will be added. When the div has been added, just add the class.
Here's something I made which comes in handy in annoying cases like this where it's difficult to tell when the element you need has finished loading in: https://gist.github.com/DanWebb/8b688b31492632b38aea
so after including the function it'd be something like:
var interval = 500,
stopTime = 5000,
loaded = false;
setIntervalTimeout(function() {
if($('.dynanicElementClass').length && !loaded) {
$('.dynanicElementClass').addClass('checkbox');
loaded = true;
}
}, interval, stopTime);
It's not perfect and I'm sure there are better solutions out there but in most cases like this it does the job.
I have a application that loads CSS styles dynamic based on user preference. I use requirejs to load these like:
require(['css!dir/styles'], function(){ .... });
this works great but I don't want to show the screen until all the styles have fully initialized.
I've added a CSS class to the body of the page called hide-page and then remove that class when the callback occurs. Like:
setTimeout(function() { $(document.body).removeClass('hide-page'); }, 100);
but even with the settimeout, the page still loads jumbled until everything has initialized. I was thinking about doing a setInterval and checking if a particular style has been applied to a node like:
setInterval(function(){
if($(document.body).style('background'') === "#FFFFFF"){
$(document.body).removeClass('hide-page');
}
}, 10);
but thats kinda hackey. Is there a better solution anyone has to accomplish this?
You don't say how you're hiding the page content, but that could be the problem if you're using display:none.
Try visibility:hidden instead. This will allow the browser to allocate the space needed to construct the page, so you shouldn't see the jumbled FOUC.
I am using some JS code to transform my menu into a drilldown menu.
The problem is before it runs the JS you see a BIG UGLY mess of links. On their site its solved by putting the js at the top. Using recommendations by yahoo/YSlow i am keeping the JS files at the bottom.
I tried hiding the menu with display:none then using jquery to .show(), .css('display', ''), .css('display', 'block') and they all lead up to a messsed up looking menu (i get the title but not the title background color or any links of the menu)
How do i properly hide a div/menu and show it after being rendered?
In the <head> place this:
<script>document.documentElement.className = 'js';</script>
Now, it will .js class to your html element. And it will be the very first thing done by the javascript on the page.
In your CSS you can write:
.js #menu {
display:none;
}
And then:
$(document).ready(function() {
$('#menu').css('display','block').fancyMenu();
});
This is an excellent technique, that allows you to make your pages "progressively enhanced", if your user has JavaScript disabled – she will still be able to see the content, and you can also separate non-JS styling with styling, that is relevant only for JS version of your menu, perhaps "position:absolute" and things like that.
At the top of your page put:
<script type="text/javascript">
document.write('<style type="text/css">');
document.write('#mylinks { display:none; }');
document.write('</style>');
</script>
And at the end of your "processing", call $('#mylinks').show();
document.write is evaluated as the DOM is processed, which means this dynamic style block will be registered in the style rules before the page is first displayed in the viewport.
This is a good case where progressive enhancement works really well - if your users have JS available & enabled, you hide the links until they are ready; but if not, they are still available, albeit ugly.
Life will be gentler with you if you try not to make pages that look like "a big ugly mess" without javascript. Have a heart.
Whatever yahoo says, it would probably be worth it for you to insert a little script that adds a style element with a few rules to the head of ypur document, before the body renders.
I found the solution. I should let the links be hidden with css then .show() BEFORE the ddMenu code executes instead of after. The ddMenu seems to check the parents width and sinces its hidden i guess its 0. The time between .show() and ddMenu is fast enough not to show the ugly links (on my machine/browser). The the majority of the time (page loading, http req for the JS files, JS compiling/exec etc) the links are hidden so it looks pretty good.
$(function () {
$('.menuT1').show(); //do it before not after in this case.
$('.menuT1 > ul').ddMenu({
Well, If you are familiar with jquery then I would do something like this
$("#mybuttom").click(function() {
$("#mydiv").hide(); //hide the div at the start of process
$.post( "mypostpage.php",
{ testvar: testdata },
function(data) {
//callback function after successful post
$('#mydiv').show(); //show it again
}
);
});