mercredi 5 août 2015

Binding mouse events to dynamically created select


I have created select tag dynamically in jquery function. I want to bind the mouse events to it. I have dynamically created the selct tag

function loadValues()
{
var sel='<select id="flavor_slct'+index+'" class="popper" data-popbox="pop1"     

onclick="alert()">'+flavor_fetched_string+'</select>';
$("#attach").append(sel);

}

I have tried using the .on Jquery function. Still events are not triggered.


$("body").on("hover","Select",function(
alert("hovered");
)};

How should i bind events to dynamically created elements.?



via Chebli Mohamed

Check if textbox contains a number


I'm currently working on a digital assistant website which is based around JavaScript and jQuery. The user can type in questions or tell the assistant things into the textbox and the assistant will respond with something relevant to the input. What I am planning to implement is to check if the textbox contains a number (intager) and if it does some sort of function will run. The concept sounds fairly simple and but I am having trouble. I have been searching around for a bit but I can't seem to find anything which will work with my code.

I will add my JavaScript and the nessacary parts of the HTML. But I am warning you, the code is messy.

JavaScript:

// JavaScript Document
function submitted() {
    var srch = document.getElementById("srch");
    command();
    getPlaceHolder();
    srch.value = "";
}

function searchKeyPress(e) {
    e = e || window.event;
    if (e.keyCode == 13) {
        //document.getElementById('btn').click();
        submitted();
    }
}

function goBtn() {
    submitted();
}

function refreshBtn() {
    getWelcome();
}

function stClock() {
    window.setTimeout("stClock()", 1000);
    today = new Date();
    self.status = today.toString();
}

function getWelcome() {
    var ar = new Array(20)
    ar[0] = "What's on your mind?";
    ar[1] = "How can I help?";
    ar[2] = "Anything you need help with?";
    ar[3] = "Ask me anything";
    ar[4] = "What can I help you with?";
    ar[5] = "What would you like me to do?";
    ar[6] = "What can I do for you?";
    ar[7] = "Need help with anything?";
    ar[8] = "Need someone to talk to?";
    ar[9] = "I'm here to help";
    ar[10] = "Anything you need to know?";
    ar[11] = "How else can I help?";
    ar[12] = "What can I do now?";
    ar[13] = "Need anything?";
    ar[14] = "Any problems you need solving?";
    ar[15] = "Hello, how do you do?";
    ar[16] = "Hi there";
    ar[17] = "Hi, I'm aurum";
    ar[18] = "Hello there";
    ar[19] = "How do you do?";
    var now = new Date();
    var sec = now.getSeconds();
    document.getElementById('output').innerHTML = ar[sec % 20];
}

function getPlaceHolder() {
    var ar = new Array(20)
    ar[0] = "What's on your mind?";
    ar[1] = "How can I help?";
    ar[2] = "Anything you need help with?";
    ar[3] = "Ask me anything";
    ar[4] = "What can I help you with?";
    ar[5] = "What would you like me to do?";
    ar[6] = "What can I do for you?";
    ar[7] = "Need help with anything?";
    ar[8] = "Need someone to talk to?";
    ar[9] = "I'm here to help";
    ar[10] = "Anything you need to know?";
    ar[11] = "How else can I help?";
    ar[12] = "What can I do now?";
    ar[13] = "Need anything?";
    ar[14] = "Any problems you need solving?";
    ar[15] = "Hello, how do you do?";
    ar[16] = "Hi there";
    ar[17] = "Hi, I'm aurum";
    ar[18] = "Hello there";
    ar[19] = "How do you do?";
    var now = new Date();
    var sec = now.getSeconds();
    document.getElementsByName('srch')[0].placeholder=ar[sec % 20];
}

function command() {
        var srchVar = document.getElementById("srch");
        var srch = srchVar.value;
        var t = srch;
        var outputElement = document.getElementById('output');
        if (srch == '') {
            outputElement.innerHTML = "How can I help you, if you don't say anything?";
        }
        else if (srch.indexOf('about') != -1) {
            outputElement.innerHTML = "Hello, I'm Aurum. I was designed by Omar Latreche to help people answer their questions. However, I also like to talk to people aswell as answer their questions.";
        }
        else if (srch.indexOf('time') != -1) {
            outputElement.innerHTML = 'The current time according to your computer is' + ShowTime(new Date());
        }
        else {
            if (confirm("I am sorry but for some reason I don't understand. You could either repeat that or would you like to search Google for that instead?") == true) {
                window.open('http://ift.tt/1ANNWBe' + srch, '_blank');
            }
            else { /* Nothing */ }
        }
    }
    //Show time in 12hour format
var ShowTime = (function() {
    function addZero(num) {
        return (num >= 0 && num < 10) ? "0" + num : num + "";
    }
    return function(dt) {
        var formatted = '';
        if (dt) {
            var hours24 = dt.getHours();
            var hours = ((hours24 + 11) % 12) + 1;
            formatted = [formatted, [addZero(hours), addZero(dt.getMinutes())].join(":"), hours24 > 11 ? "PM" : "AM"].join(" ");
        }
        return formatted;
    };
})();

And the HTML:

<!DOCTYPE html>
<html>
<body onload="getWelcome(); getPlaceHolder();">
    <div class="output" id="output">
        An error has occoured. Please make sure you have JavaScript enabled in your browser.
    </div>
    <div class="cont">
        <div class="ui-widget">
            <div class="search-cont">
                <input class="search-field" id="srch" name="srch" onkeypress="searchKeyPress(event);" placeholder="ask me anything" spellcheck="false"> <input class="refresh" onclick="refreshBtn()" title="Refresh the conversation" type="button"> <input class="go" onclick="goBtn()" type="button">
            </div>
        </div><br>
    </div>
</body>
</html>

I really appreciate any help provided. Thanks, Omar.

PS. I apologies for the long paragraph but that is the only way I could think to explain what I need.

PPS. If you need any more information on my project just incase, the URL is http://ift.tt/1InGUrg



via Chebli Mohamed

Copying a email will returns html


I've created a list of different email links, however when i'm on the page trying to copy a email it will return email with the tags aswell is there any javascript code or something like this that can avoid this?



via Chebli Mohamed

Calling PHP Function through JavaScript with Parameter


I have a function in a separate PHP page to add information to a MySql database. However if I want to pass in a paramater which is only available in my JavaScript file.

PHP Function in ModelBrowse.php

function databaseAdd($lockval)
{
    include_once('../dbConnect.php'); 

    $con = connect();
        if (!$con) {
            trigger_error(mysqli_error($con), E_USER_ERROR);
            die('Could not connect: ' . mysqli_error($con));
        }
        if ($lockval = "locked")
        {
        $sql = "INSERT INTO model(lock) VALUES ('lock')";
        }

        if ($lockval = "unlocked")
        {
        $sql = "INSERT INTO model(lock) VALUES ('unlock')";
        }


        mysqli_query($con, $sql)

        mysqli_close($con);
}

I want to call databaseAdd in my JavaScript file. I know I must use AJAX but I am confused on how I must do this.



via Chebli Mohamed

Delay in function calling


The code is:

setTimeout(function () {
    $(id_lastchild).click();
    $("#upload_download_doc").hide();
}, 150);
setTimeout(function () {
    $(id_lastchild).click();
    $("#upload_download_doc").hide();
}, 100);

but I want to do above in a function like

function click_hide_Scroll(){
        $(id_lastchild).click();
        $("#upload_download_doc").hide();
}

Implementation which I am looking for is

delay(100).click_hide_Scroll().delay(100).click_hide_Scroll();

that means after 100ms delay call function after completion of it and 100ms delay call that function again.. Is it possible? or any other code to do this?



via Chebli Mohamed

Active menu Changer on Sticky Bar


I have designed a Parallax Page with Sticky Menu bar. I need to change the active menu on scrolling. I have made it to change the active class on Click event. But I need it to do for the scroll event.

Here is my HTML Code

<div class="main-menu">

    <ul>             
        <li><a class="active" href="#" data-delay="2000" data-appear="false" data-scrollto="#intro-slideshow">Home</a></li>
        <li><a href="#" data-delay="2000" data-appear="false" data-scrollto="#overview">Features</a></li>
        <li><a href="#" data-delay="2000" data-appear="false" data-scrollto="#categories">Categories</a></li>
        <li><a href="#" data-delay="2000" data-appear="false" data-scrollto="#contact">Contact Us</a></li>
    </ul>

</div>

Here is my JQuery Code for Onclick Active Menu Changer

$('*[data-scrollto]').click(function(){

        $( "a" ).removeClass( "active" );
        $(this).addClass("active");

        var dest = $(this).data('scrollto');                
        var pixels = $(dest).offset().top - 70;         
        var ms = Math.round(1000 + pixels/5);

        $('html, body').animate({               
            scrollTop: pixels
        }, ms, 'easeOutQuint');

    }); 

How do I change the active class on Scroll Event with the Data-Scrollto attribute ?



via Chebli Mohamed

multiple html pages with different display time in same iframe


i have 5 html pages and an iframe.

i need to display the html pages in an iframe with specific display time for each page. the delay should include the time for loading the i frame container. say first page have a display time of 10 sec 2nd page a display time of 20 sec ,3rd page a display time of 30 sec and so on.

how do i display all these pages bound to there display time. ?

i have tried many ways to add the load time my including iframe.load in the code but it causes some wiered recursions which alters the display time



via Chebli Mohamed

How to automatically sum input value boxes on each row in a HTML table


I have an HTML table with columns of input boxes(Quantity, Price, Discount and Total). I made a JS function for adding as many rows as I need. I would like to make the Total column, for each row, to display automatically the value of this formula:

(Quantity * Price) - ( Quantity * Price * (Discount/100)) .

I tried numerous JavaScript code, but I have been unable to get anything to correctly work.

HTML:

<table id="myTable">
<tr>
<th width="65%"></th>
<th align="center" width="5%">Q<br>-ty</th>
<th align="center" width="10%">Price,</br>$</th>
<th align="center" width="5%">Discount,<br>%</th>
<th align="center" width="15%">Total, $<br>(Without tax)</th>
</tr>
<tr>
<td width="65%"><input class="Left" size="100" type="text" name="Description"></td>
<td align="center" width="5%"><input type="number" name="quantity" min="1" max="99"></td>
<td align="center" width="10%"><input type="number" name="summ" min="0" max="999999"></td>
<td align="center" width="5%"><input type="number" name="rate" min="0" max="100"></td>
<td align="center" width="15%"><input align="center" type="number" name="total" min="0" max="99999999"></td>
</tr>
</table>
<button onclick="addRow()">Add Row</button>

Javascript:

function addRow() {
    var table = document.getElementById("myTable");
    var row = table.insertRow();
    var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);
    var cell3 = row.insertCell(2);
    var cell4 = row.insertCell(3);
    var cell5 = row.insertCell(4);
    cell1.innerHTML = "<input class=\"Left\" size=\"100\" type=\"text\" name=\"Description\">";
    cell2.innerHTML = "<div align=\"center\"><input type=\"number\" name=\"quantity\" min=\"1\" max=\"99\"></div>";
    cell3.innerHTML = "<div align=\"center\"><input type=\"number\" name=\"summ\"  min=\"0\" max=\"999999\"></div>";
    cell4.innerHTML = "<div align=\"center\"><input type=\"number\" name=\"rate\"  min=\"0\" max=\"100\"></div>";
    cell5.innerHTML = "<div align=\"center\"><input type=\"number\" name=\"total\" min=\"0\" max=\"99999999\"></div>";
}

My code on FIDDLE.



via Chebli Mohamed

Why I need to click twice on the submit button to submit my form?


I have a form which is validated with jquery and once it's submitted I want to call a function (track_forms function to track it with Mixpanel).

It's working alright except one thing: I have to click twice to the button to submit the form. The first click doesn't do anything. I guess there's a problem using submitHandler since the issue came after implementing that.

Does anybody has an idea what's the issue?

Thanks

  $.validator.addMethod(
    'ContainsAtLeastOneNumber',
    function (value) { 
        return /[0-9]/.test(value); 
    },  
    'Please enter at least 8 characters containing numbers and letters.'
);

$.validator.addMethod(
    'ContainsAtLeastOneLetter',
    function (value) { 
        return /[a-z]/.test(value); 
    },  
    'Please enter at least 8 characters containing numbers and letters.'
);


$('#signupForm').validate({    
rules: {
    email: {
        required: true,
        email: true
    },
    password: {
        minlength: 8,
        ContainsAtLeastOneNumber: true,
        ContainsAtLeastOneLetter: true,
        required: true
    },
    confirmPassword: {
        required: true,
        equalTo: "#password"
    },
    terms: {
        required: true,
    }
},
messages: {
    email: "Please enter a valid email address.",
    password: {
      required: "Please enter at least 8 characters containing numbers and letters.",
      minlength: "Please enter at least 8 characters containing numbers and letters.",
    },
    confirmPassword: {
      required: "Please enter at least 8 characters containing numbers and letters.",
      equalTo: "The passwords are not matching.",
    },
    terms: {
        required: "You must agree with our Terms of Service.",
    },
},
highlight: function(element) {
    var id_attr = "#" + $( element ).attr("id") + "1";
    $(element).closest('.form-group').removeClass('has-success').addClass('has-error');
    $(id_attr).removeClass('glyphicon-ok').addClass('glyphicon-remove');         
},
unhighlight: function(element) {
    var id_attr = "#" + $( element ).attr("id") + "1";
    $(element).closest('.form-group').removeClass('has-error').addClass('has-success');
    $(id_attr).removeClass('glyphicon-remove').addClass('glyphicon-ok');         
},
errorElement: 'span',
    errorClass: 'help-block',
    errorPlacement: function(error, element) {
        if (element.attr('name') == 'terms' ) {
        error.insertAfter(".some-class");
        } else {
        error.insertAfter(element);
        }
    },
submitHandler: function(form) {
 mixpanel.track_forms("#signupForm", "Created Account");
    } 
 });



via Chebli Mohamed

jquery plugin scrollspy change detecting position of an element


i'm using jquery-scrollspy http://ift.tt/1aoi2SL for showing the active navigation on a one page website. The script changes if a section enter into the viewport. Unfortunately i have very small sections so there are more than one showing on the viewport -> means, the navigation swip to fast. is there any solution to change the point where enter/exit the section, f.e. if the section is entering the navigation-position (the navigation is horizontally fixed at the top). Is this possible with this class or any ideas?

thanks for help.

best regards thomas



via Chebli Mohamed

how to reload data without refreshing page with pagination


i do have the code below, and im trying to update the data without refreshing the page with pagination. i have tried many thing taken from stackoverflow but not succeeded.

PHP--

<?php
$auth_id = mysql_real_escape_string($_GET['id']);
$auths_id = mysql_real_escape_string($_GET['id']);
/**
 * @link: http://ift.tt/pVlYMq
 */
    //connect to the database
    include_once ('db/config_books.php'); 
    //get the function
    include_once ('includes/function_ulema.php');



        $page = (int) (!isset($_GET["page"]) ? 1 : $_GET["page"]);
        $limit = 5;
        $startpoint = ($page * $limit) - $limit;

        //to make pagination
        $statement = "books b LEFT OUTER JOIN authors_compile_rel ar ON (b.id = ar.book_id)
        where b.status = 1 AND ( b.auth_id = '".$auth_id."' OR b.t_auth_id = '".$auth_id."' OR ar.auth_id = '".$auth_id."' )";
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://ift.tt/kkyg93">
<html xmlns="http://ift.tt/lH0Osb" xml:lang="en" lang="en">

<head>
    <title>Pagination</title>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <link href="css/pagination_ulema.css" rel="stylesheet" type="text/css" />
    <link href="css/grey_ulema.css" rel="stylesheet" type="text/css" />

    <style type="text/css">
        .records {
            width: 510px;
            margin: 5px;
            padding:2px 5px;
            border:1px solid #B6B6B6;
        }

        .record {
            color: #474747;
            margin: 5px 0;
            padding: 3px 5px;
            background:#E6E6E6;  
            border: 1px solid #B6B6B6;
            cursor: pointer;
            letter-spacing: 2px;
        }
        .record:hover {
            background:#D3D2D2;
        }


        .round {
            -moz-border-radius:8px;
            -khtml-border-radius: 8px;
            -webkit-border-radius: 8px;
            border-radius:8px;    
        }    
    </style> 
</head>

<body>

    <div class="records round">

        <?php
            //show records
            $query = mysql_query("
SELECT 
b.id, b.unique_name, b.native_name, b.auth_id, b.status, b.create_date, ar.auth_id 
FROM books b LEFT OUTER JOIN authors_compile_rel ar ON (b.id = ar.book_id)
WHERE 
b.status = 1 AND ( b.auth_id = ".$auth_id." OR b.t_auth_id = ".$auth_id." OR ar.auth_id = ".$auth_id." )
ORDER by b.id DESC 
            LIMIT {$startpoint} , {$limit}");

            while ($row = mysql_fetch_assoc($query)) {
        ?>
            <div class="record round"><?php echo $row['id']; echo " - "; echo $row['unique_name']; ?></div>
        <?php    
            }
        ?>
    </div>

<?php
    echo pagination($statement,$limit,$page);
?>

</body>
</html>

and i do have the function file of pagination below:

<?php
$auth_id = mysql_real_escape_string($_GET['id']);
$auths_id = mysql_real_escape_string($_GET['id']);
/**
 * @link: http://ift.tt/pVlYMq
 */

   function pagination($query, $per_page = 10,$page = 1, $url = '?' ){        
        $query = "SELECT COUNT(*) as `num` FROM {$query}";
        $row = mysql_fetch_array(mysql_query($query));
        $total = $row['num'];
        $auth_ids   =   $row['auth_id'];
        $adjacents = "2"; 

        $page = ($page == 0 ? 1 : $page);  
        $start = ($page - 1) * $per_page;                               

        $prev = $page - 1;                          
        $next = $page + 1;
        $lastpage = ceil($total/$per_page);
        $lpm1 = $lastpage - 1;

        $pagination = "";
        if($lastpage > 1)
        {   
            $pagination .= "<ul class='pagination'>";
                    $pagination .= "<li class='details'>Page $page of $lastpage</li>";
            if ($lastpage < 7 + ($adjacents * 2))
            {   
                for ($counter = 1; $counter <= $lastpage; $counter++)
                {
                    if ($counter == $page)
                        $pagination.= "<li><a class='current'>$counter</a></li>";
                    else
                        $pagination.= "<li><a href='{$url}page=$counter&id={$_GET['id']}'>$counter</a></li>";                   
                }
            }
            elseif($lastpage > 5 + ($adjacents * 2))
            {

                if($page < 1 + ($adjacents * 2))        
                {
                    for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
                    {
                        if ($counter == $page)
                            $pagination.= "<li><a class='current'>$counter</a></li>";
                        else
                            $pagination.= "<li><a href='{$url}page=$counter&id={$_GET['id']}'>$counter</a></li>";                   
                    }
                    $pagination.= "<li class='dot'>...</li>";
                    $pagination.= "<li><a href='{$url}page=$lpm1&id={$_GET['id']}'>$lpm1</a></li>";
                    $pagination.= "<li><a href='{$url}page=$lastpage&id={$_GET['id']}'>$lastpage</a></li>";     
                }
                elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2))
                {
                    $pagination.= "<li><a href='{$url}page=1&id={$_GET['id']}'>1</a></li>";
                    $pagination.= "<li><a href='{$url}page=2&id={$_GET['id']}'>2</a></li>";
                    $pagination.= "<li class='dot'>...</li>";
                    for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++)
                    {
                        if ($counter == $page)
                            $pagination.= "<li><a class='current'>$counter</a></li>";
                        else
                            $pagination.= "<li><a href='{$url}page=$counter&id={$_GET['id']}'>$counter</a></li>";                   
                    }
                    $pagination.= "<li class='dot'>..</li>";
                    $pagination.= "<li><a href='{$url}page=$lpm1&id={$_GET['id']}'>$lpm1</a></li>";
                    $pagination.= "<li><a href='{$url}page=$lastpage&id={$_GET['id']}'>$lastpage</a></li>";     
                }
                else
                {
                    $pagination.= "<li><a href='{$url}page=1&id={$_GET['id']}'>1</a></li>";
                    $pagination.= "<li><a href='{$url}page=2&id={$_GET['id']}'>2</a></li>";
                    $pagination.= "<li class='dot'>..</li>";
                    for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++)
                    {
                        if ($counter == $page)
                            $pagination.= "<li><a class='current'>$counter</a></li>";
                        else
                            $pagination.= "<li><a href='{$url}page=$counter&id={$_GET['id']}'>$counter</a></li>";                   
                    }
                }
            }

            if ($page < $counter - 1){ 
                $pagination.= "<li><a href='{$url}page=$next&id={$_GET['id']}'>Next</a></li>";
                $pagination.= "<li><a href='{$url}page=$lastpage&id={$_GET['id']}'>Last</a></li>";
            }else{
                $pagination.= "<li><a class='current'>Next</a></li>";
                $pagination.= "<li><a class='current'>Last</a></li>";
            }
            $pagination.= "</ul>\n";        
        }


        return $pagination;
    } 
?>

Please help me with integration of the javascript to load the data with pagination without refreshing page.



via Chebli Mohamed

How can I show a foundation.css dropmenu by jQuery


I tried to write a nav bar with foundation.css, but the sub-menu does not show when mouse move on.

The question is, how can I show the sub-menu of test in this webpage.

I tried to change the visibility, display, z-index, left, but nothing happend.



via Chebli Mohamed

Maintain dropdownlist viewstate after postback


My set up:

  1. I have a GridView, and two DropDownList in each TemplateField of it.
  2. GridView is enclosed withing Ajax UpdatePanel.
  3. I am populating one DropDownList from selection of other DropDownList using JQuery.

    I works fine till now. But when I submit this form I get EventValidation error. I have solved it by setting EnableEventValidation of Page to false. Error is gone. Fine. But I can't take selected value of DropDownList that was bound using Jquery, also populated values are gone. Seems like ViewState problem to me. Am I wrong? Any suggestions please?



via Chebli Mohamed

Detect if page is scrolled on document load


I'm using the scrollTop to detect if the users scrolls then fadeIn an element:

$(document).ready(function() {
    // scroll to top
    $(window).scroll(function() {
        if ($(this).scrollTop() >= 700) { // if page is scrolled more than 700px
            $('#return-to-top').fadeIn(200);
        } else {
            $('#return-to-top').fadeOut(200);
        }
    });
});

It works well if the user loads the page and then scroll, but if the user is already below the 700px and reload or goes back to the same page the element doesn't fadeIn automatically on document load. It seems that it is not detecting the page is already scrolled.

Any idea what could be the problem with my code?



via Chebli Mohamed

parseFloat returns nan


I'm trying to get rid of currency sign in order to calculate new price using parseFloat, but it returns nan for some reason.

var pricePerUser = "£19.99";
pricePerUser = parseFloat(pricePerUser) * 3;
console.log(pricePerUser); //Returns NaN



via Chebli Mohamed

Getting the value of a view property in the template


Using MVC and Nhibernate i am getting the property

x => CurrentRecord.Reference

This line is in the view itself but the view html is being rendered by a template. In the template i need to specify that if the value being rendered in the HTML is a number then align to the right and if the value is text then align left.

At the moment the html is using the below:

@{
 var propName = this.ViewData.TemplateInfo.HtmlFieldPrefix;
}
  <input class="form-control input-sm align right" data-bind="value: @propName" required />

This allows me to bind the element properly using jQuery but doesn't actually get me the value of the property.

How would i get the value of the property from the view model?



via Chebli Mohamed

Canvas Draw need to save as video


I created a canvas drawing project,now i need to save that as a video file when am click save button.I need to save as video from begin to end



via Chebli Mohamed

How to do 2 animations at once with jQuery


I'm working on a web project. I want to draw a div element (looks like a table) with an animation: I click on the button, then the div element appears with a small size upon the button, then it floats to "its" posion meanwhile gaining its original size. I managed to do this, but only sequentely. First the scaling, than the floating. I want these animations to do at the same time.

I use jQuery ui show() function to make the div appear and scale to its origin size, then I use the jQuery animate fuction for the floating.

I tried to use the queue : false property. And I also called the .dequeue() function, but it woulnd't work as I wanted so.

I'll appreciate any pieces of advice. Thanks in advance. Cheers.

 $('#matrix').animate({
        top: positionTop,
        left: positionLeft,
    });
    $('#matrix').show("scale", { percent: 100, direction: 'both', origin: ['top', 'left'] }, 2000);
    $('#matrix').animate({
        top: positionTopAim,
        left: positionLeftAim
    });

Fiddle here: LINK



via Chebli Mohamed

Hide / customize cursor during HTML5 drag


I'd like to customize the mouse cursor during a HTML5 drag operation because it's one thing to setDragImage to something representing the object being dragged (not in IE) but it generally looks pretty awful having the standard mouse cursor superimposed. This is especially the case when the 'DragImage' is small and there is no way to control the opacity of the 'DragImage'.

I have various CSS cursors specified on the drop target but these get disabled / ignored by both Chrome and Firefox during a drag. This leaves us with the standard unattractive arrow-and-dotted-box.

Here's the fiddle: http://ift.tt/1Unb0Tg

Here's the HTML:

<img draggable id="i" src="http://ift.tt/1gJHVmN"/>

<table>
    <tr>
        <td class="a">Copy</td>
        <td class="b">None</td>
    </tr>
    <tr>
        <td class="c">Move</td>
        <td class="d">Crosshair</td>
    </tr>
</table>

Here's the CSS:

td {
    padding: 30px;
    font-size: 2em;
    font-family: arial;
    border: 3px solid white;
    background-color: #eee;
    border-spacing: 10px;
}

.a {    cursor: copy;}
.b {    cursor: none;}
.c {    cursor: move;}
.d {    cursor: crosshair;}

img {
    cursor: move;
    cursor: -moz-grabbing;
}

Here's the jQuery:

var i = $('#i');

i.on('dragstart', function(e) {
    e.originalEvent.dataTransfer.setData('text', 'foo');
    e.originalEvent.dataTransfer.setDragImage(this, this.offsetWidth/2, this.offsetHeight/2);
});

$('td').on('dragenter, dragover', function(e) {
   e.preventDefault();
   e.stopPropagation();
    return false;
});

$('td').on('drop', function(e) {
    $(this).append(i);
    e.preventDefault();
});

Is there a way to hide or change the mouse cursor during a HTML5 drag?



via Chebli Mohamed

How to animate input box and btn search


I have the following code and animation is not working as expected. On focusout inputbox animates nice but btn_search returns to its place without animation.

 <div class="form-group">
     {!!Form::text('pretraga',null,['id'=>'pretraga','class'=>'form-control','placeholder'=>'pretraga...'])!!}
 </div>
 <div class="form-group">
     {!!Form::button('<span class="glyphicon glyphicon-search"></span>', ['id'=>'btn_search', 'class'=>'btn btn-default'])!!}
 </div>

             $("#pretraga").click(function (e) {
                    e.preventDefault();
                    $(this).animate({width: '250px'}, "slow");
                });
             $("#pretraga").focusout(function(e){
                e.preventDefault();
                $(this).animate({width: '100%'}, "slow");
             });



via Chebli Mohamed

Jqgrid - Uncaught RangeError: Maximum call stack size exceeded


Dynamic Column width According to Its Content

I tried adjusting the column width dynamically according to the content this way ,by finding characters length of each row ,then finally getting the max length out of it and setting it to grid column width.

loadComplete : function () {
                $("#grid").on("jqGridAfterLoadComplete jqGridRemapColumns", function () {
                var $this = $("#grid"),
                colModel = $this.jqGrid("getGridParam", "colModel"),
                iCol,
                iRow,
                rows,
                row,
                n = $.isArray(colModel) ? colModel.length : 0;
                var rowData = "";
                var rowDataLen="";
                var input = [];
                var divs = $( "div" );
                var colWidth=125;
                for (iCol = 0; iCol < n; iCol++) {
                            input = [];
                            for (iRow = 0, rows = this.rows; iRow < rows.length; iRow++) {
                                        row = rows[iRow];
                                        rowData = $(row.cells[iCol]).find(divs).html();
                                        if(rowData != undefined)
                                            rowDataLen = rowData.length;
                                        input.push(rowDataLen);
                            }
                            var finalWidth =  Math.max.apply(null, input);
                            if(finalWidth < colWidth)
                                finalWidth = colWidth;
                            $("#grid").jqGrid("setColWidth", iCol, finalWidth);
                            var gw = $("#grid").jqGrid('getGridParam','width');
                            $("#grid").jqGrid('setGridWidth',gw);
                       }                    
            });     
        },

and it is working fine.

However it is too slow and getting Uncaught RangeError: Maximum call stack size exceeded

error when I have more records like 500.

Can anyone help to tweak the above solution so that it can be faster?

Here is my HTML Code:

<td role="gridcell" style="text-align:left;" title="Hot-forged Hot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forged." aria-describedby="grid_test">
<div style="max-height: 120px">Hot-forged Hot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forged.</i><br><br><i>tttttttttttttttttttttttttttttttt</i></div></td>

I am actually finding the max character size of the div content..will that be reduced if i directly take title attribute of tag as i have the same data in both the tags?

colum model formatter for fixed row height:

formatter : function(cellvalue){ if(cellvalue == undefined || cellvalue == null) { cellvalue = ""; } return '' + cellvalue + ''; },

Or how can i reduce the performace of this code? Please help..



via Chebli Mohamed

Select text of li elements through JQuery


How can I select the text from list elements through JQuery.I want the same functionality as that of .select() in javascript,but that is only applicable to editable text areas/input boxes, can someone guide me ,for the same functionality with list elements

I want the list text to be selected on click



via Chebli Mohamed

Autocomplete multiple fields based on one field (jQuery Autocomplete)


My JSON information:

{
"RES_ID":"2622959",
"PROP_ID":"76055",
"RES_CHECK_IN":"2015-04-21",
"RES_CHECK_OUT":"2015-04-25",
"RES_N_ADULTS":"6",
"RES_GUEST_FIRSTNAME":"Nicolas",
"RES_GUEST_LASTNAME":"Prantzos"
}

I want the RES_ID as autocomplete for the following input:

<input id="reservation_id" class="ui-autocomplete-input form-control" />

And when the input reservation_id will be filled take the rest RES_CHECK_IN and RES_CHECK_OUT and autofill them in

<input type="text" class="form-control" name="start">
<span class="input-group-addon">to</span>
<input type="text" class="form-control" name="end">

I tried to mix ajax + autocomplete do achieve that without any luck.

 (function autocomplete_search() {
        //this function take the @res_id input
        $("#reservation_id").autocomplete({
            source: "/police/get_res"
        });
    })();

How I show RES_ID as autocomplete and how i fill the rest of the inputs based on the RES_ID?



via Chebli Mohamed

jQuery code to get checkbox length while using jQuery DataTables


I am getting wrong value while fetching the checkbox length using jQuery and jQuery DataTables.

HTML:

<table class="table table-bordered" id="dataTables-show-productList">
   <thead>
      <tr>
         <th width="5px"><input type="checkbox" name="Select All" class="chkSelectAll" /></th>
         <th>Product Information</th>
      </tr>
   </thead>
   <tbody>                 
    <c:forEach var="masterListVar" items="${masterList}">                   
      <tr>
         <td width="1%" align="center">
         <c:if test="${masterListVar.saveFlag}">
            <input type="checkbox" path="selectChecked" checked class="Projection_test" value="${masterListVar.productId}"/>
         </c:if>
         <c:if test="${!masterListVar.saveFlag}">
            <input type="checkbox" path="selectChecked" class="Projection_test" value="${masterListVar.productId}"/>
         </c:if>
         </td>
         <td>${masterListVar.productInfo}</td>
      </tr>
   </c:forEach>   
   </tbody>
</table>

JavaScript:

$('#dataTables-show-productList').DataTable({
   width:'100%'
   , responsive : true
   , "bSort" : false 
});


$('.chkSelectAll').click(function () {
   $('.Projection_test').prop('checked', $(this).is(':checked'));
});

$('.Projection_test').click(function () {
   if ($('.Projection_test:checked').length == $('.Projection_test').length) {
     $('.chkSelectAll').prop('checked', true);
   }
   else {
     $('.chkSelectAll').prop('checked', false);
   }
});


$('#FavouriteList').click(function (e) {
   var selectedRow = $('.Projection_test');

   alert($('.Projection_test:checked').length);
   e.preventDefault();
});

When paginating, while selecting only 12 values. in the alert it showing only 2 when i kept in the 2 page and testing.



via Chebli Mohamed

jquery plugin - define a variable options that contain other variables or functions


I'd like to know if is possibile in a jquery plugin define a variable options that contain other variables or functions

$.fn.Plugin.defaults = {
    pagelabels: "Page " + current + " of " + totalPages;
    total: "The total is " + getTotal.call(this);
};

$.fn.Plugin = function(options) {
    var options = $.extend(true, {}, $.fn.Plugin.defaults, options);

    return this.each(function() {

        var current = 10;
        var totalPages = 100;

        $('#page').text(options.pagelabels);
        $('#total').text(options.total);
    });
};

function getTotal() {
    return 2000;
}

Is there a way to do this? Thank you



via Chebli Mohamed

jquery script not working well with turbolinks


I have an index in my app, whose view includes some filtering options. Once these are selected, results are being filtered. It's all nice except that when first getting into the index, all this scripting does not work and the page needs to be reloaded in order to function properly. I have tried using the jquery.turbolinks gem, didn't do anything. Any suggestions?

index.html.erb:

<% content_for :on_document_ready_js_script do %> #this being yielded on layout

    $("#er_filters").change(function() {
        var url = "/examinee_registrations.js";  // grab the URL from the form action value.
    $.get(url, $("form").serialize()); 
   });

<% end %>


<div id="title">
    <h1> 
        <%=t("examinee_registration.title")%>
        <% if @location_id %>
            <span id="<%=@location_id%>"> <%=t("for") + " #{Location.find(@location_id).name}" %> </span>
        <% end %>
    </h1>
</div>
<br>
    <%= form_tag examinee_registrations_url(format: "xls"), method: :get do %>
        <div id="er_filters">
            <br>
            <%= hidden_field_tag 'location_id', @location_id %>
            <%= label_tag 'from_date', t("from_date")+':' %>
            <%= date_field_tag "from_date" %>
            <br>
            <%= label_tag 'to_date', t("to_date")+':' %>
            <%= date_field_tag "to_date" %>
            <br>
            <%= label_tag 'hide_open', t("examinee_registration.hide_open")+':' %>
            <%= check_box_tag "hide_open", true, false  %>
            <br>
            <%= label_tag 'hide_closed', t("examinee_registration.hide_closed")+':' %>
            <%= check_box_tag "hide_closed", true, false  %>
        </div>
        <%= submit_tag t('export_to_excel') %>
    <% end %>

<br>
<%= link_to create_title('examinee_registration.single')+"ה", new_examinee_path %>
<hr>


<div id='er_div' >
    <%= render 'examinee_registrations' %>
</div>

application.js:

//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//= require turbolinks
//= require bootstrap-sprockets
//= require_tree .

index.js.erb:

$("#er_div").html("<%= escape_javascript(render 'examinee_registrations') %>");



via Chebli Mohamed

How to change a seleclist options from another selectlist?


I have two seleclists. I want to filter second selectlist options from first select list.

Here is the code:

$(document).ready(function() {
    $('#sehir').change(function() {
        var sehir = $(this).find('option:selected').text();
        var options = $('#ilce').filter('[label=' + sehir + ']');
        $('#ilce').html(options);
    });
});

And first selectlist:

<select name="sehirid" id="sehir" class="form-control">
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
    <option value="3">Option 3</option>
</select>

Second selectlist:

<select name="ilceid" id="ilce" class="form-control">
    <optgroup label="Option 1">
        <option parent="Option 1" value="1">Option 1</option>
        <option parent="Option 1" value="2">Option 2</option>
        <option parent="Option 1" value="3">Option 3</option>
    </optgroup>
    <optgroup label="Option 2">
        <option parent="Option 2" value="1">Option 1</option>
        <option parent="Option 2" value="2">Option 2</option>
        <option parent="Option 2" value="3">Option 3</option>
    </optgroup>
    <optgroup label="Option 3">
        <option parent="Option 3" value="1">Option 1</option>
        <option parent="Option 3" value="2">Option 2</option>
        <option parent="Option 3" value="3">Option 3</option>
    </optgroup>
</select>

But this code is not working. What's wrong?



via Chebli Mohamed

Jquery.Change not working


I am having some trouble with $.change in jQuery.

HTML

<button class="btn">Reset</button>
<p id="chg" class="change">Click Me</p>
<div class="onchange"></div>

JS

$('.btn').on('click', function() {
  $('.change').text('Click Me');
  $('.onchange').text('');
});
$('.change').on('click', function() {
  $('.change').text('Nearly There');
});
$('.change').on('change', function() {
  $('.onchange').text("Nice One");
});

Here is the link to Codepen

Basically what should happen is when "Click Me" is clicked the text will change to "Nearly There" then straight after "Nice One" should appear below.

However this isn't happening, I've tried both

$('.change').on('change', function() {});
$('.change').change(function() {});

And neither work.

Note The code I have supplied is my test code, and is all relevant to what I'm trying to achieve.

Update I wasn't aware the .change only worked for form controls, which would explain why it wasn't working.

Solution CreMedian - Suggested the solution that I was looking for.

$('.change').on('DOMSubtreeModified', function() { });

I have updated the CodePen for future reference.



via Chebli Mohamed

eq(0) is not a valid selector with $.each


<select class="qty">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>


<select class="qty">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>

I have 2 select tag and I want to update them with an array, means chaging the selected to correct value, but why in my attempt below eq() is not working with my loop?

selectedArr = [2,3];

$.each(selectedArr,function(i,obj){
console.log(obj);
$('.qty:eq('+i+')').prop('selected',true);
});



via Chebli Mohamed

Hover to clear and reset Interval for jQuery slideshow


I'm making a simple jQuery slideshow, and have it working except for one thing- I'd like to pause on hover and restart on mouseleave.
I've tried the .hover method as well as .mouseenter + .mouseleave methods, and consistently find that it works correctly for one repetition, but on the second attempt exhibits all kinds of wacky behavior- the mouseenter behavior may not fire, and on mouseleave the timing is completely broken. With a few versions, the slideshow has also gotten stuck between two images, rather than going through all of the images in the set. Here's a codepen with the whole code including HTML and CSS, and I'll post just the js here - the problematic hover code is at the bottom.

  $('#thinger').ready(function() {

  //index images and figure captions with dog class
  $('#thinger img.dog').each(function(idx) {
    $(this).attr('img-index', idx);
    dog_max = idx;
  });
  $("#thinger figcaption.dog").each(function(idx) {
    $(this).attr("figcap-index", idx);
  });

  //index images and figure captions with cat class
  $('#thinger img.cat').each(function(idx) {
    $(this).attr('img-index', idx);
    cat_max = idx;
  });
  $("#thinger figcaption.cat").each(function(idx) {
      $(this).attr("figcap-index", idx);
    });

  //set image height to 70% of window height
  $('#thinger img').css('height', ($(window).innerHeight() * 0.7));

  //vertically centers images if they have a height smaller than the size of the containing figure
  var vertical_center = function(img) {
  var displayHeight = $('#thinger').innerHeight();
  if (displayHeight > img.outerHeight()) {
      img.css({'margin-bottom': (displayHeight - img.outerHeight()) / 2});
    } else {
      img.css({
        'margin-top': ''
      });
    }
  };
  //Resets image size and vertical center when window is resized
  $(window).resize(function() {
    $('#thinger img').css('height', ($(window).innerHeight() * 0.7));
    vertical_center($('#thinger img'));
  });

  do_next_image(1);

  //set interval to advance
  pic_interval = setInterval(do_next_image, 5000);
  });
  //when spans with attribute of "control" are clicked, run the advance script, passing in the +1 or -1 value
  $('span[control]').on('click', function() {
  do_next_image(parseInt($(this).attr('control')));
  //Clear the interval so the viewer has time to see the new image
  clearInterval(pic_interval);
  //reset the interval and run the advance script
  pic_interval = setInterval(do_next_image, 5000);
  })

  var pic_interval;
  var current_index = 0;
  var max_index;

  function do_next_image(iter) {
  //use appropriate max value
  if ($("#dogButton").hasClass("active")) {
    max_index = dog_max;
  } else if ($("#catButton").hasClass("active")) {
    max_index = cat_max;
  }
  //If no value is passed in for iter, assume increase by one
  if (iter === undefined) {
    iter = 1;
  }
  //give var prev the value of the LAST current_index before it gets increased in the next step
  var prev = current_index;

  //increase current_index by iter which will have a -1 effect if iter is negative
  current_index += iter;
  //if  the rotation is at the end, start back at the beginning
  if (current_index > max_index) {
    current_index = 0;
  }
  //if current_index has a value below 0, give it a meaningful value
  else if (current_index < 0) {
    current_index = max_index + 1 + iter;
  }

  function switch_image() {
  //find the image and figure caption with the index prev and change its display to block
  $("img.active[img-index='" + prev + "']").css("display", "block");
  $("figcaption.active[img-index='" + prev + "']").css("display", "block");

  //find the image and figure caption with the index prev and fade them out
    $('img.active[img-index="' + prev + '"]').animate(
      {opacity: 0}, 1000);
    $("figcaption.active[figcap-index='" + prev + "']").animate(
      {opacity: 0}, 1000);

    //Change new image from no display to block
    $('img.active[img-index="' + current_index + '"]').css("display", "block");
    $("figcaption.active[figcap-index='" + current_index + "']").css("display", "block");

    //Change previous image from block display to none
    $('img.active[img-index="' + prev + '"]').css("display", "none");
    $("figcaption.active[figcap-index='" + prev + "']").css("display", "none");

    //find the image that corresponds with current_index and fade in
    $('img.active[img-index="' + current_index + '"]').animate(
      {opacity: 1}, 800);
    $("figcaption.active[figcap-index='" + current_index + "']").animate(
      {opacity: 1}, 800);
  }

  //switch image sets on button click
  $("#dogButton").click(function() {
    //stop previous animation
    $("img, figcaption").stop(true, true).fadeOut("slow");
    //remove previous image
    $("img, figcaption").css("display", "none");
    clearInterval(pic_interval);
    //remove active class from all elements
    $("img, figcaption, button").removeClass("active");
    //add active class to appropriate elements
    $(".dog , #dogButton").addClass("active");
    //run switch_image steps  
    switch_image();
    //reset interval
    pic_interval = setInterval(do_next_image, 5000);
  })

  $("#catButton").click(function() {
    $("img, figcaption").stop(true, true).fadeOut("slow");
    $("img, figcaption").css("display", "none");
    clearInterval(pic_interval);
    $("img, figcaption, button").removeClass("active");
    $(".cat, #catButton").addClass("active");
    switch_image();
    pic_interval = setInterval(do_next_image, 5000);
  })
  switch_image();

//This is the hover pause part that's behaving strangely!

$("#thinger img").mouseenter(function(){
  clearInterval(pic_interval);
  $("#thinger").stop();
});
$("#thinger img").mouseleave(function(){
  pic_interval = setInterval(do_next_image, 5000);
  switch_image();
});
}



via Chebli Mohamed

Rating module makes an input radio change


I have a rating module on my webpage :

<div class="rating">
   <label for="rate_1"class="glyphicon glyphicon-star"><input type="radio" id="rate_1" name="rating" value="1"></label>
   <label for="rate_2"class="glyphicon glyphicon-star"><input type="radio" id="rate_2" name="rating" value="2"></label>
   <label for="rate_3"class="glyphicon glyphicon-star"><input type="radio" id="rate_3" name="rating" value="3"></label>
   <label for="rate_4"class="glyphicon glyphicon-star"><input type="radio" id="rate_4" name="rating" value="4"></label>
   <label for="rate_5"class="glyphicon glyphicon-star"><input type="radio" id="rate_5" name="rating" value="5"></label>
</div>

and when I click on 4th or 5th star, I would like the validated radio been checked in my validation :

<ul class="validation">
     <li class="success-hover"><label for="id_validation_1"><input class="success" type="radio" id="id_validation_1" name="validation"><i class="fa fa-check"></i>Validated</label></li>
     <li class="danger-hover"><label for="id_validation_2"><input class="danger" type="radio" id="id_validation_2" name="validation"><i class="fa fa-close"></i>Rejected</label></li>
     <li class="info-hover"><label for="id_validation_3"><input type="radio" id="id_validation_3" name="validation"><i class="fa fa-spinner"></i>Partially completed</label></li>
     <li class="warning-hover"><label for="id_validation_4"><input type="radio" id="id_validation_4" name="validation"><i class="fa fa-clock-o"></i>Expired</label></li>
</ul>

I started with some Jquery code :

if ($("input[name=rating][value=4]").prop('checked', true)||$("input[name=rating][value=5]").prop('checked', true)) {
    $('.success').prop('checked', true);
}
else $('.success').prop('checked', false);

But it doesn't work... Please help me ! ^^



via Chebli Mohamed

Posting to a remote form assistance required


I have a simple form on a Hubspot system. I use the details on HubSpot for marketing purposes, so I do need a HubSpot form instead of a normal form on my platform.

This is my setup:

  1. www.thedomain.com -- this is out website running on HubSpot
  2. app.thedomain.com -- this runs our Php platform

On the HubSpot site (www.thedomain.com) I have a form with the following fields that works 100% to capture user date.

  1. First Name
  2. Last Name
  3. Email Address
  4. Username (this is not really being used in HubSpot)

On Submit, I want to have a javascript that takes the completed fields and posts them on a similar form on my App (app.thedomain.com). The fields must exactly be the same as the ones completed on HubSpot.

In short, when you click submit and there are not errors, you are redirected to the app.thedomain.com and the form there is pre-populated - all you do is click "Sign Up" again.

I need some guidance in the right place. I can run javascript/jquery on HubSpot.



via Chebli Mohamed

Rendering single mesh color change - THREEJS


I have a grid that contains boxes, very similar to http://ift.tt/1BUa9lL. Now I initiated a hover state when a box on the scene is mouseover it turns the background gray. Which is great! Except when I multiple "box" on the grid and I go to change the material background color of the hovered item, it renders all of the "box's" with a gray background.

Heres what I am doing:

var voxel = new THREE.Mesh( this.cubeGeometry, this.cubeMaterial );
voxel.position.copy( intersect.point ).add( intersect.face.normal );
voxel.position.divideScalar( 50 ).floor().multiplyScalar( 50 ).addScalar( 25 );
this.scene.add( voxel );
this.blocks.push( voxel );
var domEvents   = new THREEx.DomEvents(this.camera, this.renderer.domElement)
// DOM events for inside 3d rendering
domEvents.addEventListener(voxel, 'mouseover', this.onDocumentMouseOverCube.bind(this),false);
domEvents.addEventListener(voxel, 'mouseout', this.onDocumentMouseOutCube.bind(this),false);

Here we create our box - we than give it eventListeners for that specific mesh. Once this mesh is hovered over, our mouseover is executed:

this.mouse.x = ( event.origDomEvent.clientX / this.renderer.domElement.width ) * 2 - 1;
this.mouse.y = - ( event.origDomEvent.clientY / this.renderer.domElement.height ) * 2 + 1;

this.raycaster.setFromCamera( this.mouse, this.camera );
var intersects = this.raycaster.intersectObjects( this.blocks );
if ( intersects.length > 0 ) {

    var intersect = intersects[ 0 ];

    if ( intersect.object != this.plane ) {
        console.log(intersect.object);


        // update color on hover
        intersect.object.material.color.setHex(this.colorHover);
        console.log("hover color");
        this.render();
    }
}

Now this works great, the only issue is - this.render() is called (this.renderer.render( this.scene, this.camera )) like it should be. But when I have multiple box's on it goes ahead and changes every single background color of each box I have even logged all my objects to confirm object.material.color is the gray hex for only one box and that not all of the box's are being set, which proves to be true. I am sending the correct data over. So I am assuming it has to do with the rendering of the actual engine?

Suggestions?



via Chebli Mohamed

jquery ajaxStart call inside msgbox Success function


I am doing a File upload using a confirmation box with Ok and Cancel using MsgBox. The code is as follows.

$.msgBox({
    title : title,
    content : message,
    type : type,
    buttons: [{
        type: "submit", 
        value: "Ok"
    },{        
        type: "cancel", 
        value: "Cancel"
    }],
    success: function (result) {
        // alert(result);
        if (result == "Ok") {
            $(document).ajaxStart(function(){
                $.blockUI({ 
                    message: $('.box'), 
                    css: { 
                        padding: '20px', 
                        backgroundColor: '#fff', 
                        '-webkit-border-radius': '10px',
                        '-moz-border-radius': '10px',
                        opacity: .6, 
                        color: '#fff'    
                    }    
                }); 
            });
            $(document).ajaxStop($.unblockUI); 
        }

        $(document).ajaxForm({
            // My Upload Code 
        }
    }
});

So when I click Ok button I have to start ajax and block my UI. Its a file Upload So my file upload Progress will be loaded upto the ajax gets stopped.

Problem

When I click on upload A confirmation Box should come and when I click OK then the code sequence should go like ajaxStart should start and my file upload AJAXFORM should progress continue, when the AJAXFORM request stops unblockUI will activate.

Problem is that I am not able to give these sequential code inside success of the $.msgBox(). On one click it is not working, on the second click only the form is getting uploading. When the same set of code is used normally it is working Fine but not inside the success.

Is there any option to use ajaxForm,AjaxStart call inside success of another jquery plugin?



via Chebli Mohamed

Escape user-generated chat messages but render links


User enter chat messages, which gets rendered directly to the page using Mustache templates. Obviously, HTML should be escaped to prevent HTML injection, but then again links should be rendered as <a href='...'>.

There are different approaches I've tried to use {{{ ... }}} to return the unescaped HTML content, which means the link would get rendered and I need to take care of HTML escaping myself. Is there a safe way of doing that without relying on a half-baked solution I write myself?

jQuery.text() would be great, but I guess it will render the <a> again as text.

What else can I do here?



via Chebli Mohamed

Send multiple chekbox items to Angular Controller


I'm trying to make a view wich allow me to send invitation via email to google contacts using google contacts api & javascript

for (var index = 0; index < result.length ; index++){
  var name= result[index];
  $(".email").append('<div><span class="part left">'+result[index]+'</span><span class="part right">


What i need is to send the values of the selected checkboxs to angular controller

in my controller when i var_dump the ng-model it always says undefined. Any suggestions ?

 var emails = [];
  emails.push(checkboxModel.name);
  $scope.data = emails;
  console.log(emails);



via Chebli Mohamed

Make one single page scrollable using fullPage.js


I'm trying to make one single section (page) with large content scrolling using fullPage.js. There is a method described here http://ift.tt/1Un9joY, to set option scrollOverflow: true. But this option applies to all sections, this is not what needed. I searched throw methods http://ift.tt/QUtWx5 and found one $.fn.fullpage.setFitToSection(false);, but It's not for my case.

Is there any way to switch scrollOverflow option, depending on nextIndex (onLeave : function(index, nextIndex, direction))?

I found in source code

  /**
    * Sets fitToSection
    */
    FP.setFitToSection = function(value, type){
        setVariableState('fitToSection', value, type);
    };

So I think adding next code might help

  /**
    * Sets setScrollOverflow
    */
    FP.setScrollOverflow = function(value, type){
        setVariableState('scrollOverflow', value, type);
    };

Or more universal version

   /**
    * Sets any option variable
    */
    FP.setOptionVariable = function(variable, value, type){
        setVariableState(variable, value, type);
    };

But all this requires fullpage source code change. Any other ideas?



via Chebli Mohamed

Understanding Java code and make it jQuery. (loginpage)


I'm trying to understand a login-procedure to a balance-only login page at a bank. There is already a project that has the procedure in Java, but i'm not too familiar with it so I cant fully understand it. (http://ift.tt/1IkcNmO)

I would like to make it in jQuery.

My attempt is:

<html>
<head>
<script src="http://ift.tt/1HheyD3"></script>
</head>
<script>
var user_id="8311117173";
var password="secret";
var pemUrl="http://ift.tt/1IkcNmQ";
var loginUrl="http://ift.tt/1IkcPuY";
var epochTime=Date.now();
$.ajax({
    async: false,
    cache: false,
    type: 'post',
    data: ({
        'p_tranid':epochTime,
        'p_errorScreen':'LOGON_REPOST_ERROR',
        'n_bank':'',
        'empty_pwd':'',
        'username': user_id,
        'password': password
    }),
    url: loginUrl,
    success: function (response) {
        console.log(response);
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        console.log(XMLHttpRequest.responseText);
        console.log(XMLHttpRequest);
        console.log(textStatus);
        console.log(errorThrown);
    }
});
</script>
</html>

The response should include "LOGON_OK", but it does not.

I've seen that in the Java-code, there is something about a certificate-file (http://ift.tt/1KQ3lv4) The code that I'm talking about is below. What is the procedure that I'm missing?

protected LoginPackage preLogin() throws BankException, IOException {
    urlopen = new Urllib(context, CertificateReader.getCertificates(context, R.raw.cert_okq8));
    Date d = new Date();
    List<NameValuePair> postData = new ArrayList<NameValuePair>();
    response = urlopen
            .open("http://ift.tt/1IkcNmQ");
    //p_tranid is the epoch time in milliseconds
    postData.add(new BasicNameValuePair("p_tranid", Long.toString(d.getTime())));
    postData.add(new BasicNameValuePair("p_errorScreen", "LOGON_REPOST_ERROR"));
    postData.add(new BasicNameValuePair("n_bank", ""));
    postData.add(new BasicNameValuePair("empty_pwd", ""));
    postData.add(new BasicNameValuePair("user_id", getUsername().toUpperCase()));
    postData.add(new BasicNameValuePair("password", getPassword()));
    return new LoginPackage(urlopen, postData, response,
            "http://ift.tt/1IkcPuY");
}



via Chebli Mohamed

find a specific text in tr td jquery using contains [duplicate]


This question already has an answer here:

This is my fiddle of finding a text in tr.

I used

var reports = $('table#reports > tbody');
var tr1 = reports.find('tr:has(td:contains("First Name"))');

to find the text but even if the text does not exist it still alerts that it exists. To check if it exist i created an if

if (tr1) {
    alert('exist');
 } else {
    alert('not');
 }



via Chebli Mohamed

Passing two numbers for each visible image


I've got multiple images with a common class. The user is able to hide or make them visible.

I need to pass two numbers for each visible image. The starting number should be 0 and should be a continues number. This is what I've done so far.

The current output is 0,1,1,2,2,3....

I want the output to be 0,1,2,3,4,5,....

$('#passNum').click(function(){
    var curNumber= 0;
    $('.visibeimage:visible').each(function(){
          useNumber(curNumber++);
    });
});

Note: the first number should be 0



via Chebli Mohamed

Jquery number increment to tag


I am trying to write a variable that holds the main value of the paragraph tag as seen here:

<button id="button">random words</button>
   <p id="inc">0</p>
   <script>
       $(document).ready(function(){
        $('#button').on("click", function(){
          var oldVal = $("#inc")
          $('#inc').text( oldVal + 1)
        });
       });
   </script>

How do I turn the '#inc' into a number so i can do a + 1 increment?



via Chebli Mohamed

Single page scrolling nav items don't work on different page


I have built a wordpress theme that accommodates both a single page layout and separate pages (i.e. pages that navigate away from the front page). As with most single page layouts, you click on a nav item and it scrolls to that section. I have achieved this by giving the section an id and then putting that id in the menu link (i.e. #about or #contact).

This code then scrolls to the page section:

jQuery(document).ready(function($){
jQuery('a[href*=#]').click(function (e) {
    e.preventDefault();

    var navHeight = jQuery('#header').height();
    var id = jQuery(this).attr('href');
    var scrollTo = jQuery(id).offset().top-navHeight;

    jQuery('html,body').animate({
        'scrollTop': scrollTo
    }, 500);
});

});

The problem I'm having, is when I navigate away from this page, and then click on a menu item that typically would scroll down the page - the menu items do not work.

I have tried using the full URL and also using '/#id' but neither of those options work. Is there a workaround I can use here?



via Chebli Mohamed

Jquery slideToggle() to a certain height?


I have tried the below coding to slide my div up and down:

$("#toggle").click(function(e) {
    e.preventDefault();
    $("#numbers").slideToggle();
});

How do we let it to only slide until certain height for example half of my div?



via Chebli Mohamed

listen loaded event to each resource (all scripts, css, images, etc)


I am working to a page loaded percentage bar based on every single resource in the page loading: I mean monitoring every image, or script, css, etc and use its "loaded event" to increase the general page loaded percentage

I have readed in some posts that is difficult to monitor the loaded event of some elements, so my question is how to do it using javascript / jQuery? What strategy can I use to achieve that result?

I tried something like this, but actually it is not working well

function calc(element){
    console.log(element.outerHTML);
    progress++;
    var loadingStatus = ( progress * 100 / totalLength );
    console.log(loadingStatus);
    document.getElementById('loadingBar').style.width = loadingStatus+'%';
}

document.onreadystatechange = function(){
    if(document.readyState == "interactive"){

        progress = 0;

        var scriptElements = document.querySelectorAll('script[src]');
        var linkElements = document.querySelectorAll('link');
        var otherElements = document.querySelectorAll('style, img');
        totalLength = (scriptElements.length + linkElements.length + otherElements.length);

        for(var i=0; i<scriptElements.length; i++){
            var source = scriptElements[i].src;
            scriptElements[i].remove();
            var newScript = document.createElement('script');
            newScript.setAttribute('src', source);
            newScript.setAttribute('onload','calc(this);');
            document.head.appendChild(newScript);
        }

        for(var i=0; i<linkElements.length; i++){
            var source = linkElements[i].href;
            linkElements[i].remove();
            var newLink = document.createElement('link');
            newLink.setAttribute('href', source);
            newLink.setAttribute('rel', 'stylesheet');
            newLink.setAttribute('onload','calc(this);');
            document.head.appendChild(newLink);
        }

        for(var i=0; i<otherElements.length; i++){
            otherElements[i].setAttribute('onload','calc(this);');
        }

    }
}



via Chebli Mohamed

Wordpress - getting media library events


I'm developing a gallery and this is the JS code for the media library:

jQuery(document).ready(function(){

var custom_uploader;

jQuery('#upload_image_button').click(function(e) {

    //forbid default behaviour of the event
    e.preventDefault();

    //If the uploader object has already been created, reopen the dialog
    if (custom_uploader) {
        custom_uploader.open();
        return;
    }

    //Extend the wp.media object to create the window
    custom_uploader = wp.media.frames.file_frame = wp.media({
        title: 'Choose Image',
        button: {
            text: 'Choose Image'
        },
        multiple: false
    });

    //When a file is selected, grab the URL and set it as the text field's value
    custom_uploader.on('select', function() {
        // Get media attachment details from the frame state
        attachment = custom_uploader.state().get('selection').first().toJSON();
        jQuery('#upload_image').val(attachment.url);
    });

    //Open the uploader dialog
    custom_uploader.open();

   });
});

Now I need to get the image ID to arrange images from the media library which will take part on the gallery using PHP so I thought an AJAX/JSON call should be good to pass data from the media window created with wp.media after the user clicks on "Choose image".

How can I get this event? I cant' find a list of events associated to wp.media but in the code above there's:

custom_uploader.on('select', function() {...}

so I think there could be a sort of custom_uploader.on('buttonclick' function(){...}, isn't it?

Otherwise how can I accomplish it?

Thank you!



via Chebli Mohamed

Sticky subnav when scrolling past, breaks on resize


I have a main header that is fixed to the top and I have a subnav (which on the real site is for anchor links within the page) which is fixed to the bottom of the window. I then have a hero image which is the height of the window minus the height of the header and minus the height of the subnav. When a user scrolls past the subnav at the bottom, it then sticks to the top just after the main navigation. This all works pretty well at the moment.

Here's an extracted version of how it works on the site that's under development: http://ift.tt/1MNOnVW.

However, the one bug is that when the window is resized, the subnav's position isn't recalculated and so ends up positioned either too high or too low.

I can refactor for the subnav's position by binding an additional window resize event:

// Refactor subnav measurements on window resize
$( window ).resize(function() {

  var windowH = $(window).height();
  var stickToBot = windowH - $('#subnav').outerHeight(true);

  var scrollVal = $(this).scrollTop();
  if ( scrollVal > stickToBot - $('.navbar').outerHeight(true) ) {
      $('#subnav').css({'position':'fixed','top' :'80px'});
  } else {
      $('#subnav').css({'position':'absolute','top': stickToBot +'px'});
  }

});

This works for the initial position, but after scrolling and then resizing the window, the positioning is incorrect: http://ift.tt/1K3ANbG

I know I'm missing something very obvious here but what is it?!



via Chebli Mohamed

update data on mysql using ajax


I'm trying to send the id of an image when a user click on it using ajax. Then in the update.php file I'd like to update the id of the image. I'm new on ajax, so I'm not able to figure out my error.

$(document).ready(function(){
$('.show_people_image .love').on('click', function() {

     var id = $(this).attr('id');
     var idpage = "<?php echo $id ?>";
    var sVar1 = encodeURIComponent(id);
    var sVar2 = encodeURIComponent(idpage);
    var sVar3 = "<?php echo $_SESSION['aaa'] ?>";
    var sVar4 = "<?php echo $_SESSION['bbb'] ?>";

     if (sVar1 == sVar2) {
    $.ajax({
        type: "POST",
        url: "update.php",
        data: {lid:sVar1, ml:sVar3, mem:sVar4},
        success: function(data) {
            alert(data);
            },
        error: function () {
        alert('error');
        }  
     });    
     } 
});
});

The update.php file is:

if (isset($_POST['lid']) AND isset($_POST['ml']) AND isset($_POST['mem'])) {

include 'models/connexion_sql.php';


$loveid = $_POST['lid'];

if ($_POST['ml']) {
$str = $_POST['ml'].','.$loveid;
}
else {
$str = $loveid;
}


$sql = 'UPDATE users SET myl= :myl WHERE email = :email';
$req = $bdd->prepare($sql);
$req->bindParam(':email', $_POST['mem'], PDO::PARAM_STR);
$req->bindParam(':myl', $str, PDO::PARAM_STR);
$req->execute();

echo $str;

}  

If I put an echo in the upload.php file before the prepare($sql) the request is successful, otherwise the request fail.



via Chebli Mohamed

Moment.js display hour time ago with minutes


Is there a way to display hours with minutes? ex: 2 hours 40 minutes ago.

Right now it just displays 2 hours ago

Here is a fiddle

<script src="http://ift.tt/t0Y3fx"></script>
<script src="/js/moment.js"></script>
<script>
  $(document).ready(function(){
    var then = $('#then'),
        date = moment(new Date(then.attr('data-date'))),
        update = function(){
                   then.html(date.fromNow());
                 };

    update();
    setInterval(update, 60000);
  });
</script>



via Chebli Mohamed

Value of submitted input is empty


I want to submit some data which I attach to an input element. The server get's this element, with correct ID, but it has no value.

<form id="sub_form" method="post" action="acc_manage.lp"> 
    <input type="text" name="container" id="sub_inp" value=""> </input>
</form>

sub_inp receives its input from a specific event, which calls:

function execute_submit(){
    $("#sub_inp").val(JSON.stringify(foo));
    // .val() returns a stringified object 
    console.log( $("#sub_inp").val() )
    if ($("#sub_inp").val() != "") {
        $("#sub_form").submit();
  };

Value of the post request on server-side is this:

post={ container={} }, formdata={}, errtag={} }

Why is this and how can I fix it? I am using jQuery 2.1.3



via Chebli Mohamed

Dynatree: Expanding parent node of selected child node is removing real 'checked' attribute


I'm all out of ideas and have no ideas on how to amend this problem. The issue is occurring in the expand function of Dynatree:

 onExpand: function (select, dtnode) {
             $("#tree :checkbox").addClass("hidden");
                //$("#chb-" + dtnode.data.key).attr("checked", dtnode.isSelected()).addClass("hidden");
                    if (dtnode.isSelected()) {
                        $("#chb-" + dtnode.data.key).attr('checked', 'checked').addClass("hidden");
                    } else {
                        $("#chb-" + dtnode.data.key).removeAttr("checked").addClass("hidden");
                    }
            },

when my tree is loaded all the outlay is correct - even the selected checkboxes that are set to be checked upon load.

(a) href="#" class="dynatree-title" title="Country" style="background: none;"> (input type="checkbox" id="chb-key7-2-1" name="Country: 14" value="Item 7-2-1" class="hidden" checked="checked")Australia (/a)

note the checked value is correctly set here - however when i then go to expand the parent of this node (I've set the tree to collapsed upon load finish) the 'checked' attribute is removed. this also happens if I normally select a node then collapse and re-expand the parent of that node.

Is there any solution for this I've looked and tried creating my own kind of solution but to no avail. Also could someone explain why the checked value is being removed when I expand the parent node of the selected child?

key tree settings:

$("#tree").dynatree({
            persist: false,
            checkbox: true,
            selectMode: 3,
            activeVisible: true,
            clickFolderMode: 2,
            noLink: false,

            onActivate: function (node) {
                node.data.expander.hide = true; //hide the expanders so i can use the text to expand
                node.render(true);
            },



via Chebli Mohamed

samedi 25 avril 2015

Imacro - Error -921 with a field-wrapper


I m recording an imacro macro.

Here is my script:

VERSION BUILD=8920312 RECORDER=FX
TAB T=1
TAG POS=1 TYPE=EM ATTR=TXT:Lui<SP>écrire
TAG POS=1 TYPE=INPUT:TEXT FORM=ID:postform ATTR=ID:subj CONTENT=Hello
TAG POS=1 TYPE=TEXTAREA FORM=ID:postform ATTR=ID:text CONTENT=Bonjour
TAG POS=1 TYPE=INPUT:CHECKBOX FORM=ID:postform ATTR=ID:inclure CONTENT=YES
TAG POS=1 TYPE=INPUT:SUBMIT FORM=ID:postform ATTR=*

Here is the code in the body of the page:

<div id="form-subj" class="rc-form-field ">
<label for="subj">Sujet :</label>
<span class="field-wrapper">
<input id="subj" type="text" value="" name="subj" maxlength="40">
</span>
</div>

I attached a capture too of the page.

I suppose that the field-wrapper is causing the error.


Angularjs 1.3.15 - Updating $scope after Promise Returned


I'm learning angularjs and trying to update nav bar with user name after login, but the user name does not appear. Here is the process I am following:

  1. User logs in successfully.
  2. After 'then' in login promise (to make sure promise is returned), get user profile via factory which returns the user profile.
  3. After 'success' in getting user profile, save profile to $scope.user so that DOM is updated.

Here is HTML for Nav Bar (not sure if it matters but this is placed into index.html using ng-include on page load):

<nav ng-controller="menuController">
    <div class="navbar-header">
        <a class="navbar-brand" href="index.html">
            Admin Site
        </a>
    </div>
    <ul >
        <li ><span>Welcome {{ user.firstName }}</span></li>
    </ul>
  </div>
</nav>

Here is the menuController js file:

    angular
    .module('myApp')
    .controller("menuController", ['$scope', '$auth', '$timeout', '$window', 'toaster', 'Account',
        function UserCtrl($scope, $auth, $timeout, $window, toaster, Account) {

            $scope.user = [];

            $scope.login = function () {
                $auth.login({email: $scope.email, password: $scope.password})
                    .then(function(response){
                        toaster.pop('success', "Logged In", "You have successfully logged into the system"); // This fires correctly
                        Account.getProfile()
                            .success(function(obj){
                                $scope.user = obj;
                                console.log('User: ' + 
$scope.user.firstName);  //This Works! But user.firstName in HTML is not updated
                            });
                    })
                    .catch(function (response) {
                        toaster.pop('error', "Login Failure", response.data.message);
                    })
            };   
        }
    ]);

The problem is that the user.firstName in the navigation bar never updates with the user's first name. Am I missing something?

Thank you for any help!


Scrollable table contents html/css


I'm trying to make my table contents scrollable, I've had to create a table inside one of the table rows which means if the table has more than one row the contents isn't aligned with the correct heading as showing in the fiddle;

http://ift.tt/1HDmj4z

thead.panel-heading {
    background-color: #242a30;
    border-color: #242a30;
    border-bottom: 1px solid #242a30;
    border-top-left-radius: 3px;
    border-top-right-radius: 3px;
    cursor: move;
    width: 100%;
}
thead.panel-heading tr th {
    color: #ffffff;
    font-weight: 500;
    padding: 10px 40px !important;
    text-align: left;
}
tbody.panel-content {
    background-color: #f0f3f4;
}
tbody.panel-content tr td {
    padding: 10px 20px !important;
    text-align: left;
}
tbody div {
    overflow-x: hidden;
    overflow-y: scroll;
    height: 300px;
}
<table>
    <thead class="panel-heading">
        <tr>
            <th>Client</th>
            <th>Client</th>
        </tr>
    </thead>
    <tbody class="panel-content">
        <tr>
            <td>
                <div class="scrollit">
                    <table>
                        <tr>
                            <td>Alex Best</td>
                            <td>Yahoo Answers</td>
                        </tr>
                        <tr>
                            <td>Andrew Smith</td>
                            <td>Monkey Tube</td>
                        </tr>
                        <tr>
                            <td>James Harris</td>
                            <td>Limewire</td>
                        </tr>
                        <tr>
                            <td>Mike Anderson</td>
                            <td>Twitter</td>
                        </tr>
                    </table>
                </div>
            </td>
        </tr>
    </tbody>
</table>

How to obtain innerHTML of an active li link?


I want to store the innerHTML of an active menu item to display it as a title for my page. The title HTML is {{pageTitle}}, in the "container" template.

here is my (cleaned) HTML

<template name="container">
   {{pageTitle}
   {{ > SideMenu}}
</template>

<template name="SideMenu">
    <ul id="menu-items" class="nav nav-stacked nav-pills">
        <li id="menu-item-simple" class="">
            <a href="#">
                menuItem1
            </a>
        </li>
        <li id="menu-item-simple" class="">
            <a href="#">
                menuItem2
            </a>
        </li>
    </ul>
</template>

I created an helper to return the string

Template.container.helpers({
"pageTitle":function(){
    return Session.get("pageTitle");
}
});

And an event to set the string to its correct value when a menu item is clicked

Template.SideMenu.events({
    "click #menu-items":function(e,t){
        var activeItem = $(this).find("li.active")
        Session.set ("pageTitle",activeItem.children("a").innerHTML);
        console.log (activeItem.children("a").innerHTML);
    }
});

The console returns "undefined". I don't get what I am doing wrong and since I'm just beginning, I also wanted to know if I'm going the right way.


WebBrowser iframe not displays when using HttpWebRequest


I use Winform WebBrowser to load an website. The website is contains an iframe. The URL here: http://ift.tt/1v05tFk

When i use Navigate() method to load that URL. The WebBrowser display an texteditor and an iframe.

When i try to use HttpWebRequest to load the website, like this:

    HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create("http://ift.tt/1v05tFk");

    HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();

    webBrowser1.DocumentStream = myResponse.GetResponseStream();

The WebBrowser is also display an html's texteditor, but the iframe is not displayed. It just show me the iframe's URL. enter image description here Why the WebBrowser not display the iframe contents ? While the HTML,CSS,JS still work, but the Iframe not ?


Different viewport widths for landscape and portrait


My website is more or less optimized for mobile devices, however it needs a minimum width of 480 px. Using

<meta name="viewport" content="width=480">

works well, but only in portrait mode. If I switch to landscape, it uses 480 px too, which makes everything too big. Is there a way with maybe a script to switch to a higher width if landscape (mobile users only) is used? Thank you.


CSS some space at the end of the page, reason floats?


I used the class "section", inside the section are 2 elements. The first one is a div with the class "content" and the secound one is the aside. I doesn't gave the section a fixed high (the section should grow with the content inside the container "content" & the aside). I floated the container "content" to the left side and the aside to the right side.

My Problem: I gave the section a margin-bottom of 25px, but nothing happens. Thats why i marked the section with a bgcolor (bgcolor = red). But the section is only as high as the aside.

*{
    margin: 0px;
    padding: 0px;
    font-size: 16px;
    color: white;
    text-decoration: none;
}

body{
    background-color: rgb(38, 38, 38);
}

nav{
    width: 100%;
    background-color: rgb(25, 25, 25);
}


.navbar_ul{
    list-style-type: none;
    width: 800px;
    width: 1000px;
    margin: 0 auto;
}

.navbar_li{
    display: inline-block;
    margin-top: 10px; 
    margin-bottom: 10px;
    margin-right: 30px;
}

a{
    color: #666;
    display: block;
    transition: color 0.2s ease-in-out 0s;
}

a:hover{
    color: #CCC;
}

section{
    margin: 0 auto;
    margin-top: 25px;
    margin-bottom: 50px;
    width: 1012px;
    height: 1000px;
    background-color: red;
}

.content{
    width: 750px;
    border: 3px solid rgb(30, 30, 30);
    background-color: rgb(75, 75, 75);
    float: left;
}

aside{
    width: 200px;
    float: right;
}

p{
    padding: 10px;
    width: 730px;
    text-align: justify;
}

.asd{
    padding: 10px;
    text-align: justify; 
}

.header{
    width: 100%;
    background: linear-gradient(to bottom, #191919 0px, #373737 100%) repeat scroll 0% 0% transparent;
    text-align: center;
    padding: 10px 0px;
}
<!DOCTYPE html>

<html>
    <head>
        <title>XXX</title>
        <link rel="shortcut icon" href="title.png" type="image/png" />
        <link rel="stylesheet" type="text/css" href="index.css">
        <meta charset="utf-8" /> 
    </head>
    
    <body>
        <nav>
            <ul class="navbar_ul">
                <li class="navbar_li"><a href="http://www.google.de">Seite erstellen</a></li>
                <li class="navbar_li"><a href="http://www.google.de">Seite löschen</a></li>
                <li class="navbar_li"><a href="http://www.google.de">Seite bearbeiten</a></li>
            </ul>
        </nav>
        
        <section>
            <div class="content">
                <div class="header">Überschrift des Artikels</div>
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
                <div class="header">Schritt 1 "erstellen"</div>
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequatpsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
                <div class="header">Schritt 2 "bearbeiten"</div>
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
                <div class="header">Schritt 3 "löschen"</div>
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsu. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequatm dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
                
                
                
                
                
                
                
                
                
                
                
                <div class="header">Schritt 4 "mit Bild"</div>
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsu. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequatm dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
            </div>
            
            <aside>
            <a class="asd">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsu. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequatm dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</a>
            </aside>
        </section>
    </body>
</html>