i made this function:
var jq111 = jQuery.noConflict();
if (jq111("#tab-upsell_tab").find("div").length > 0){
} else {
jq111(".upsell_tab_tab").hide();
jq111("#tab-upsell_tab").hide();
}
This hide a element if are empty.
But on page load, #tab-upsell_tab appear for 1 second (if need to be hide) and i don't like it.
There is a way to load this function before this element? Or something similiar.
Edit: i accept a css solution, but how?
You should set .upsell_tab_tab and #tab-upsell_tab to display: none in your CSS. Change your JavaScript to this also:
var jq111 = jQuery.noConflict();
if (jq111("#tab-upsell_tab").find("div").length > 0){
jq111(".upsell_tab_tab").show();
jq111("#tab-upsell_tab").show();
}
This way your elements are hidden by default, and you must imperatively show them based on your logic.
Try using $.holdReady() , .ready()
$(window).load(function() {
var jq111 = jQuery.noConflict();
jq111.holdReady(true);
if (jq111("#tab-upsell_tab").find("div").length > 0) {
} else {
jq111(".upsell_tab_tab").hide();
jq111("#tab-upsell_tab").hide();
}
jq111.holdReady(false);
jq111(document).ready(function() {
// do stuff
})
})
div .length within "#tab-upsell_tab" not greater than 0
http://plnkr.co/edit/Xp2RbPe65BaFeobtTVOL?p=preview
div .length within "#tab-upsell_tab" greater than 0
http://plnkr.co/edit/ekSUelSinlM8baKQe74Y?p=preview
The DOM renders HTML, CSS, then JS. So if you want your HTML elements hidden then hide them with your CSS or you could create using a template system like mustache or in your JS code. I prefer creating them in your JS code. It makes your code cleaner and it lighter on the DOM.
Related
I have a html file with many div. Beside this I have a JQuery file too which run an AJAX request in every 30 seconds. In my JQuery If a condition met and the jQuery reloded 3 times I want to update my div-s. I tried to add a div, but it does not appear just when I reload my whole page. If I set to remove my div and not add, the JQuery removes my div, so it is very odd for me, because just the .add or .append or .html do not working. furthermore I set a class with invisibility too, and I also set that when the condition met the jQuery file remove the invisibility class, but the div do not want to appear. I am trying to create a sample code.
My html
<div class="row">
<div id="myclass" class= "invisible" >
<div <p> Please appear for me!<p></div>
</div>
</div>
My JQuery:
if (condition) {
$('#myclass').removeClass('invisible');
if (n >= 2) {
$('#myclass').addClass('invisible');
}
}
The main point is, If the conditions met the class not removes just When I reload my page. In the jQuery file the n is equal with the times when the AJAX reloaded with setInterval. My question is why my div not appear just when I reload my whole page? Also why remove without reload?
Thank you in advance the answers!
removeClass and addClass perfectly work. at first, you can check if you jQuery works, just try to write you script (with ".append",".html",".insertAfter") directly in browser console, else you can add some console.log in your code, when you change invisibility like:
console.log('removeClass');
$('#myclass').removeClass('invisible');
if (n >= 2) {
console.log('addClass');
$('#myclass').addClass('invisible');
}
for update some div content, you can use simple function for it. like -
call self page in get request, and replace div content.
function reloadMyDiv(selector){
var element = $(selector);
if(element.length===1){
$.get(window.location.href,{},function(response){
var new_page = $('<div></div>').append(response);
var new_element = new_page.find(selector);
if(new_element.length===1){
element.html( new_element.html() );
console.log('update');
}else{
console.log('need contains only one element, '+new_element.length+' found!');
}
});
}else{
console.log('need contains only one element, '+element.length+' found!')
}
};
and if you more _ not use your interval, is good practice for clear it.
var n = 0;
var myInterval = setInterval(function(){ myFunction() },30*1000);
function myFunction(){
n+=1;
//do, what you want to do
if(n>2){
clearInterval(myInterval);
}
}
i have this order form which i'm making.
Right now when someone put a coupon code I want to apply to the div of the old price a style or class (line-through) and i though I had it right...here is what i'm doing.....any suggestion why it might not be working? WARNING: I am really new to javascript....i've been working with CSS HTML but javascript is another story. Thanks!
if ($('#grand_amount_value').length > 1){
$("#Total_Amount_old_val").attr("style", "text-decoration:line-through");
}
Here is an example I threw together to show something like that working:
https://jsfiddle.net/pj6xwhcy/3/
function strikeOldAmt() {
var gav = $("#grand_amount_value");
if (gav.length > 0 && gav.text() != "" ){
// There is a GAV element and it is not empty, strike out the old amount!
$("#Total_Amount_old_val").css("text-decoration", "line-through");
}
}
Note: Using the "style" attribute would also wipe out any other custom styling you may have added. Using the css() function will not interfere if the style attribute is already set.
Assuming the page isn't reloading you could use a setInterval to check if the element exists.
var checkInterval = setInterval(function(){
if ($('#grand_amount_value').length){
$("#Total_Amount_old_val").attr("style", "text-decoration:line-through");
clearInterval(checkInterval);
}
},200);
Simplest clean way
$(document).on('change','#grand_amount_value',function(){
if ($('#grand_amount_value').val().length != 0){
$('#Total_Amount_old_val').css('text-decoration','line-through');
}
});
or if you need continuous check
$(document).on('keypress','#grand_amount_value',function(){
if ($('#grand_amount_value').val().length != 0){
$('#Total_Amount_old_val').css('text-decoration','line-through');
}
});
Here a jsfiddle
UPDATE: I'm sorry that my thread was misinterpreted by many users. I'll try to be more clear.
I'm using Drupal and I have created three floating banners. On the frontpage there is a block (block1) that displays one floating banner and after refresh the second one is appearing and for the third too.
Like a wrote before these banners has a little X button to stop overflow.
I've putted this script in a one of the banners and it's working great.
<script language="javascript">
function doexpand() {
document.getElementById("block1").style.overflow = "visible";
}
function dolittle() {
document.getElementById("block1").style.overflow = "hidden";
}
</script>
The real problem is that in categories pages I have #block2 and in articles #block3.
These block are displaying the same banners. The code over is working only for a one ID. In this case #block1. document.getElementById is not working for more ID's as I read from other topics.
I've tried with jQuery with two blocks idents like this:
(function ($) {
function doexpand() {
$("#block1,#block2").css("overflow","visible");
}
function dolittle() {
$("#block1,#block2").css("overflow","hidden");
}
})(jQuery);
It's not working.
The firebug/console displays: ReferenceError: doexpand is not defined.
I've tried with a single block too with jQuery like this:
(function ($) {
function doexpand() {
$("#block1").css("overflow","visible");
}
function dolittle() {
$("#block1").css("overflow","hidden");
}
})(jQuery);
and it's displaying the same error.
Note: Drupal has a different wrapping and it's like this:
(function ($) {
//your existing code
})(jQuery);
Please have a look on jQuery Selectors.
I think in your case, it is better to apply style with help of css for multiple elements. e.g. :
<script language="javascript">
function doexpand() {
$('.block').style.overflow="visible";
}
function dolittle() {
$('.block').style.overflow="hidden" ;
}
</script>
Please add class="block" to all of blocks for which you want to apply this style/function, it will apply on all of the blocks having css class "block".
jQuery?
HTML:
<div class="block2"></div>
JS:
function doExpand(selector) {
if ( $(selector).length ) {
$(selector).css({'overflow':'visible'});
}
}
Calling with non ID selector would look like this: (jQuery syntax):
doExpand('.block2');
The above code is perfectly valid in jQuery (which is a JavaScript library).
If you want to use a more typical jQuery code, you can do
$('#block1').css('overflow', 'visible');
You can expend it to multiple id like this :
$('#block1, #block2').css('overflow', 'visible');
You always can get the DOM object from a jQuery object, which means you could also have adapted your code to use jQuery selectors using
$('#block1').get(0).style.overflow="visible";
(this specific example isn't smart : no need to use jQuery if you don't use a complex selector or jQuery functions)
Pretty simple really, jQuery selection is based on css selectors for the most part. These selectors are then translated into an array of dom objects held in a jQuery object.
function doexpand() {
$("#block1").css("overflow","visible");
}
function dolittle() {
$("#block1").css("overflow","hidden");
}
You should never have more than one HTML element with the same ID (Which is why document.getElementById only returns one element)
You can just refeerence block2, block3 directly document.getElementById("block2").style.overflow="hidden" ;
Or use getElementByClassName
var elements = document.getElementsByClassName("yourClass")
Which will pick up all elements with a specific class.
If you want to use jQuery like the other answers are suggesting you can match on the element name. For example:
$('div[id^="block"]').css("overflow", "visible");
This will match all div element where their ID starts with block. You can also use other wildcards such as * for contains and $ for ends with.
Here is your Javascript Code in jQuery. I dont understand what you want do do, but you could pass the params in the function. Example under this code.
<script language="javascript">
function doexpand() {
$("#block1").css({'overflow': 'visible'});
}
function dolittle() {
$("#block1").css({'overflow': 'hidden'});
}
</script>
Here is it
<script language="javascript">
function doexpand(element) {
$("#" + element).css({'overflow': 'visible'});
}
function dolittle(element) {
$("#" + element).css({'overflow': 'hidden'});
}
</script>
Than you could call it like: doexpand("theIDofTheElement");
Alternative to document.getElementById("an_element);
in Jquery is: $("#an_element");
It will work fine in JQuery, it's just that JQuery makes things faster and less verbose.
I have a view in which I do some condition check when the page load.
if(model.count()>0){
}
I then want to call a javascript function if this condition is satisfied. How can I do this please?
I know how to do that within an html control but can this be done without any control?
Or how can i do this check in the javascript, thus having to refer to the view's model?
EDIT
This is what I have now, but the function is not recognized: The name myfunction does not exist in the current context
<script>
$(document).ready(function () {
#if (Model.Count() > 0)
{
myfunction(Model.parameter);
}
});
</script>
EDIT
I changed that to
#if (Model.Count() > 0)
{
<script type="text/javascript">
$(document).ready(function () {
myfunction(#Model.parameter);
});
</script>
}
But not working. Even if I try something like alert("test" + #Model.parameter) within the .ready(function()), it does not work.
Alternatively, I will have to write the code in the view. I tried eliminating the function and doing it in the view but i will need a way of setting the id property of html element to a variable. something like var variable = Model.param1 and then having <div id=variable></div>. But how can I set the id property to a variable?
well you can simply add the javascript in between the braces. So if you are using Razor
#if(model.count()>0){
<script>
// Javascript code here
</script>
}
What this will do is add the javascript in the page which will then be executed when the browser renders the page.
A good practice would be to execute this code when the whole document is ready. If you are using jQuery, you can do this using $(document).ready(function(){ /*Code goes here*/ });
With JavaScriptModel ( http://jsm.codeplex.com ) you could write the following code in your controller action:
if (list.Count > 0)
{
this.AddJavaScriptFunction("myjavascriptfunction", parameter);
}
You would not need to modify your view and you won't have any inline obstrusive javascript.
You could use a non-rendering html element (e.g a hidden Div) and write out the value of model.count, or even true/false to signify whether model.count > 0 into that hidden element. Then in your JavaScript you can obtain the value from the hidden element and run the condition.
Obviously this isn't appropriate if there are security implications with applying the condition. If this is the case then 'bPratik's suggestion would be more appropriate.
Try putting the if statement outside of the script tag like this
#if (Model.Count() > 0)
{
<script type="text/javascript">
$(document).ready(function () {
myfunction(#Model.parameter);
});
</script>
}
I'm trying to make some code which finds if a div exists, and if it does then have it fade away slowly. I have this to determine whether or not the div exists
if($('#error').length != 0)
{
$('#error').hide(500);
}
And that does work but only on a refresh, I've been attempting to put it in a timer like this:
var refreshId = setInterval(function()
{
if($('#error').length != 0)
{
$('#error').hide(500);
}
}, 500);
But its not getting rid of the innerHTML! I have some code which on hover alters the innerHTML of the error div so I can fill it up, but for some reason this isn't working, any advice would help!
Thank you!
$("#error").fadeOut(500);
Update:
If you are looking to check for existence:
var msg = $("#error");
if(msg.length) {
msg.fadeOut(500);
}
If you want to empty it:
$("#error").empty();
If you just want to delay 500ms then fade out, do this:
$("#error").delay(500).fadeOut();
To also empty the element, provide a callback to .fadeOut() like this:
$("#error").delay(500).fadeOut(function() {
$(this).html('');
});
There's no need to check .length, if an element that matches the selector isn't present, nothing happens :)
The div you're trying to hide likely hasn't loaded by the time your script runs. Try this; it will defer execution until the DOM is loaded:
$(document).ready(function() {
// put your code here
});
This is a good practice when using jQuery anyway.
Reference: http://docs.jquery.com/Tutorials:Introducing_$(document).ready()