Rectangle 27 21

I just had to solve the same problem. I wound up using the dialog widget from JQuery UI. I was able to implement this without using callbacks with the caveat that the dialog must be partially initialized in the click event handler for the link you want to use the confirmation functionality with (if you want to use this for more than one link). This is because the target URL for the link must be injected into the event handler for the confirmation button click.

Here's my solution, abstracted away to be suitable for an example. I use a CSS class to indicate which links should have the confirmation behavior.

<div id="dialog" title="Confirmation Required">
  Are you sure about this?
</div>

<script type="text/javascript">
  $(document).ready(function() {
    $("#dialog").dialog({
      autoOpen: false,
      modal: true
    });

  $(".confirmLink").click(function(e) {
    e.preventDefault();
    var targetUrl = $(this).attr("href");

    $("#dialog").dialog({
      buttons : {
        "Confirm" : function() {
          window.location.href = targetUrl;
        },
        "Cancel" : function() {
          $(this).dialog("close");
        }
      }
    });

    $("#dialog").dialog("open");
  });




  }); // end of $(document).ready


</script>

<a class="confirmLink" href="http://someLinkWhichRequiresConfirmation.com">Click here</a>
<a class="confirmLink" href="http://anotherSensitiveLink">Or, you could click here</a>

I wonder why this solution got accepted (and 12 upvotes). The answer to OP question is: there is no such thing which stops all javascript processing like confirm. The surprisingly accepted solution would (i'm guessing) probably randomly execute some onclick events if there are any. Probably depending on the browser as well. The whole confirmation dialog replacement seems to have no clean solution.

Absolutely agree with Toskan. Also, those users with js disabled will not get directed to anywhere if you simply rely on js based click events. However, I guess this is exactly why you are going for this, no?

For the record, I DID NOT accept this as the answer.

javascript - Is a Modal Confirm Box Using JQuery Possible? - Stack Ove...

javascript jquery modal-dialog
Rectangle 27 2

You'll need to do this with Javascript; I would recommend using jquery. Also, put the dropdown in a form, method of get and action of the controller/action URL. Then set the click event to post the form.

<form id="myForm" action="/Controller/Action" method="get">
    <select id="mySelect">...</select>
</form>

And in jquery something like:

$('#mySelect').change(function() { $('#myForm').submit(); });

Note you can use the Html.Form() helper to create the form. Also, I'd recommend having a submit button on the form, which you can hide with javascript. Then people who have JS disabled still have a way to submit the form.

asp.net mvc - Redirect to controller/view when dropdownlist changed - ...

asp.net-mvc
Rectangle 27 3

//C# class

public class DashBoardViewModel 
{
    public int Id { get; set;} 
    public decimal TotalSales { get; set;} 
    public string Url { get; set;} 
     public string MyDate{ get; set;} 
}

//JavaScript file
//Create dashboard.js file
$(document).ready(function () {

    // See the html on the View below
    $('.dashboardUrl').on('click', function(){
        var url = $(this).attr("href"); 
    });

    $("#inpDateCompleted").change(function () {   

        // Construct your view model to send to the controller
        // Pass viewModel to ajax function 

        // Date
        var myDate = $('.myDate').val();

        // IF YOU USE @Html.EditorFor(), the myDate is as below
        var myDate = $('#MyDate').val();
        var viewModel = { Id : 1, TotalSales: 50, Url: url, MyDate: myDate };


        $.ajax({
            type: 'GET',
            dataType: 'json',
            cache: false,
            url: '/Dashboard/IndexPartial',
            data: viewModel ,
            success: function (data, textStatus, jqXHR) {
                //Do Stuff 
                $("#DailyInvoiceItems").html(data.Id);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                //Do Stuff or Nothing
            }
        });

    });
});

//ASP.NET 5 MVC 6 Controller
public class DashboardController {

    [HttpGet]
    public IActionResult IndexPartial(DashBoardViewModel viewModel )
    {
        // Do stuff with my model
        var model = new DashBoardViewModel {  Id = 23 /* Some more results here*/ };
        return Json(model);
    }
}

// MVC View 
// Include jQuerylibrary
// Include dashboard.js 
<script src="~/Scripts/jquery-2.1.3.js"></script>
<script src="~/Scripts/dashboard.js"></script>
// If you want to capture your URL dynamically 

<div>
    <a class="dashboardUrl" href ="@Url.Action("IndexPartial","Dashboard")"> LinkText </a>
</div>
<div>
    <input class="myDate" type="text"/>
//OR
   @Html.EditorFor(model => model.MyDate) 
</div>

Thanks, using 'var viewModel = { Id : 1, MyDate:};' how do I get a value from a textbox on the page into the mydate parameter?

Sorry I was meaning how do I get a date from a textbox into the viewModel parameter?

Great, and sorry - once last question, how do I get the results of the ajax query to load in the "#DailyInvoiceItems" DIV?

asp.net mvc - Pass Model To Controller using Jquery/Ajax - Stack Overf...

asp.net-mvc asp.net-core asp.net-core-mvc
Rectangle 27 1

<script>
jQuery(document).ready(function() {
    jQuery(".nav.navbar-nav li").click(function(){
        jQuery(".nav.navbar-nav li").removeClass('active');
        jQuery(this).addClass('active');
        })
var loc = window.location.href;
 jQuery(".nav.navbar-nav li").removeClass('active');
    jQuery(".nav.navbar-nav li a").each(function() {
        if (loc.indexOf(jQuery(this).attr("href")) != -1) {

            jQuery(this).closest('li').addClass("active");
        }
    });
});     
</script>

<ul class="nav navbar-nav">
     <li class="active"><a href="http://localhost/wp/index.php">Main</a></li>
     <li><a href="http://localhost/wp/news">News</a></li>
     <li><a href="http://localhost/wp/contacts">Contacts</a></li>
</ul>

this just adds class "active" to all the li elements

how this can be a answer and working your end ... only those li has to be active which are clicked

Yes. But when I use the code you provided I get my css from "active" class applied to all of my menu li elements.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

php - How to assign a class "active" to the li element based on curren...

javascript php jquery addclass removeclass
Rectangle 27 1

<script>
jQuery(document).ready(function() {
    jQuery(".nav.navbar-nav li").click(function(){
        jQuery(".nav.navbar-nav li").removeClass('active');
        jQuery(this).addClass('active');
        })
var loc = window.location.href;
 jQuery(".nav.navbar-nav li").removeClass('active');
    jQuery(".nav.navbar-nav li a").each(function() {
        if (loc.indexOf(jQuery(this).attr("href")) != -1) {

            jQuery(this).closest('li').addClass("active");
        }
    });
});     
</script>

<ul class="nav navbar-nav">
     <li class="active"><a href="http://localhost/wp/index.php">Main</a></li>
     <li><a href="http://localhost/wp/news">News</a></li>
     <li><a href="http://localhost/wp/contacts">Contacts</a></li>
</ul>

this just adds class "active" to all the li elements

how this can be a answer and working your end ... only those li has to be active which are clicked

Yes. But when I use the code you provided I get my css from "active" class applied to all of my menu li elements.

php - How to assign a class "active" to the li element based on curren...

javascript php jquery addclass removeclass
Rectangle 27 1

//C# class

public class DashBoardViewModel 
{
    public int Id { get; set;} 
    public decimal TotalSales { get; set;} 
    public string Url { get; set;} 
     public string MyDate{ get; set;} 
}

//JavaScript file
//Create dashboard.js file
$(document).ready(function () {

    // See the html on the View below
    $('.dashboardUrl').on('click', function(){
        var url = $(this).attr("href"); 
    });

    $("#inpDateCompleted").change(function () {   

        // Construct your view model to send to the controller
        // Pass viewModel to ajax function 

        // Date
        var myDate = $('.myDate').val();

        // IF YOU USE @Html.EditorFor(), the myDate is as below
        var myDate = $('#MyDate').val();
        var viewModel = { Id : 1, TotalSales: 50, Url: url, MyDate: myDate };


        $.ajax({
            type: 'GET',
            dataType: 'json',
            cache: false,
            url: '/Dashboard/IndexPartial',
            data: viewModel ,
            success: function (data, textStatus, jqXHR) {
                //Do Stuff 
                $("#DailyInvoiceItems").html(data.Id);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                //Do Stuff or Nothing
            }
        });

    });
});

//ASP.NET 5 MVC 6 Controller
public class DashboardController {

    [HttpGet]
    public IActionResult IndexPartial(DashBoardViewModel viewModel )
    {
        // Do stuff with my model
        var model = new DashBoardViewModel {  Id = 23 /* Some more results here*/ };
        return Json(model);
    }
}

// MVC View 
// Include jQuerylibrary
// Include dashboard.js 
<script src="~/Scripts/jquery-2.1.3.js"></script>
<script src="~/Scripts/dashboard.js"></script>
// If you want to capture your URL dynamically 

<div>
    <a class="dashboardUrl" href ="@Url.Action("IndexPartial","Dashboard")"> LinkText </a>
</div>
<div>
    <input class="myDate" type="text"/>
//OR
   @Html.EditorFor(model => model.MyDate) 
</div>

Thanks, using 'var viewModel = { Id : 1, MyDate:};' how do I get a value from a textbox on the page into the mydate parameter?

Sorry I was meaning how do I get a date from a textbox into the viewModel parameter?

Great, and sorry - once last question, how do I get the results of the ajax query to load in the "#DailyInvoiceItems" DIV?

asp.net mvc - Pass Model To Controller using Jquery/Ajax - Stack Overf...

asp.net-mvc asp.net-core asp.net-core-mvc
Rectangle 27 119

<?xml version="1.0" encoding="iso-8859-1"?>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/themes/base/jquery-ui.css" type="text/css" />
    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/jquery-ui.min.js"></script>
    <style>
        .loading { background: url(/img/spinner.gif) center no-repeat !important}
    </style>
</head>
<body>
    <a class="ajax" href="http://www.google.com">
      Open as dialog
    </a>

    <script type="text/javascript">
    $(function (){
        $('a.ajax').click(function() {
            var url = this.href;
            // show a spinner or something via css
            var dialog = $('<div style="display:none" class="loading"></div>').appendTo('body');
            // open the dialog
            dialog.dialog({
                // add a close listener to prevent adding multiple divs to the document
                close: function(event, ui) {
                    // remove div with all data and events
                    dialog.remove();
                },
                modal: true
            });
            // load remote content
            dialog.load(
                url, 
                {}, // omit this param object to issue a GET request instead a POST request, otherwise you may provide post parameters within the object
                function (responseText, textStatus, XMLHttpRequest) {
                    // remove the loading class
                    dialog.removeClass('loading');
                }
            );
            //prevent the browser to follow the link
            return false;
        });
    });
    </script>
</body>
</html>

Note that you can't load remote from local, so you'll have to upload this to a server or whatever. Also note that you can't load from foreign domains, so you should replace href of the link to a document hosted on the same domain (and here's the workaround).

@FFish updated answer with a note about cross domain ajax. You cannot just copy'n'paste the source unless you can upload files to google.com ;)

jquery.load does not seem to ejecute the javascript contained in the remote content

regarding embedded <script></script> tags i've never got any problems to get those executed. even multiple occurences worked fine. nevertheless debugging those script chunks is indeed a hazzle, e.g. a syntax error won't show as js error in the browsers console but just avoids the script execution.

jQuery UI Dialog window loaded within AJAX style jQuery UI Tabs - Stac...

jquery jquery-ui modal-dialog
Rectangle 27 1

<script type="text/javascript">
  function uploadProgressHandler(event)
  {
    $("#loaded_n_total").html("Uploaded "+event.loaded+" bytes of "+event.total);
    var percent = (event.loaded / event.total) * 100;
    var progress = Math.round(percent);
    $("#uploadProgressBar").html(progress + " percent na ang progress");
    $("#uploadProgressBar").css("width", progress + "%");
    $("#status").html(progress +"% uploaded... please wait");
  }

  function loadHandler(event)
  {
    $("#status").html(event.target.responseText);
    $("#uploadProgressBar").css("width", "0%");
  }

  function errorHandler(event){
    $("#status").html("Upload Failed");
  }

  function abortHandler(event){
    $("#status").html("Upload Aborted");
  }

  $("#uploadFile").click(function(event)
                         {
                           event.preventDefault();
                           var file = $("#fileUpload")[0].files[0];
                           var formData = new FormData();
                           formData.append("file1", file);

                           $.ajax({url: 'http://testarea.local/UploadWithProgressBar1/file_upload_parser.php',
                                   method: 'POST',
                                   type: 'POST',
                                   data: formData,
                                   contentType: false,
                                   processData: false,
                                   xhr: function()
                                        {
                                          var xhr = new window.XMLHttpRequest();
                                          xhr.upload.addEventListener("progress",
                                                                      uploadProgressHandler,
                                                                      false
                                                                     );
                                          xhr.addEventListener("load", loadHandler, false);
                                          xhr.addEventListener("error", errorHandler, false);
                                          xhr.addEventListener("abort", abortHandler, false);

                                          return xhr;
                                        }
                                  }
                                 );
                         }
                        );
</script>

File upload progress bar with jQuery - Stack Overflow

jquery file-upload progress-bar
Rectangle 27 1

<script type="text/javascript">
  function uploadProgressHandler(event)
  {
    $("#loaded_n_total").html("Uploaded "+event.loaded+" bytes of "+event.total);
    var percent = (event.loaded / event.total) * 100;
    var progress = Math.round(percent);
    $("#uploadProgressBar").html(progress + " percent na ang progress");
    $("#uploadProgressBar").css("width", progress + "%");
    $("#status").html(progress +"% uploaded... please wait");
  }

  function loadHandler(event)
  {
    $("#status").html(event.target.responseText);
    $("#uploadProgressBar").css("width", "0%");
  }

  function errorHandler(event){
    $("#status").html("Upload Failed");
  }

  function abortHandler(event){
    $("#status").html("Upload Aborted");
  }

  $("#uploadFile").click(function(event)
                         {
                           event.preventDefault();
                           var file = $("#fileUpload")[0].files[0];
                           var formData = new FormData();
                           formData.append("file1", file);

                           $.ajax({url: 'http://testarea.local/UploadWithProgressBar1/file_upload_parser.php',
                                   method: 'POST',
                                   type: 'POST',
                                   data: formData,
                                   contentType: false,
                                   processData: false,
                                   xhr: function()
                                        {
                                          var xhr = new window.XMLHttpRequest();
                                          xhr.upload.addEventListener("progress",
                                                                      uploadProgressHandler,
                                                                      false
                                                                     );
                                          xhr.addEventListener("load", loadHandler, false);
                                          xhr.addEventListener("error", errorHandler, false);
                                          xhr.addEventListener("abort", abortHandler, false);

                                          return xhr;
                                        }
                                  }
                                 );
                         }
                        );
</script>

File upload progress bar with jQuery - Stack Overflow

jquery file-upload progress-bar
Rectangle 27 1

<script type="text/javascript">
  function uploadProgressHandler(event)
  {
    $("#loaded_n_total").html("Uploaded "+event.loaded+" bytes of "+event.total);
    var percent = (event.loaded / event.total) * 100;
    var progress = Math.round(percent);
    $("#uploadProgressBar").html(progress + " percent na ang progress");
    $("#uploadProgressBar").css("width", progress + "%");
    $("#status").html(progress +"% uploaded... please wait");
  }

  function loadHandler(event)
  {
    $("#status").html(event.target.responseText);
    $("#uploadProgressBar").css("width", "0%");
  }

  function errorHandler(event){
    $("#status").html("Upload Failed");
  }

  function abortHandler(event){
    $("#status").html("Upload Aborted");
  }

  $("#uploadFile").click(function(event)
                         {
                           event.preventDefault();
                           var file = $("#fileUpload")[0].files[0];
                           var formData = new FormData();
                           formData.append("file1", file);

                           $.ajax({url: 'http://testarea.local/UploadWithProgressBar1/file_upload_parser.php',
                                   method: 'POST',
                                   type: 'POST',
                                   data: formData,
                                   contentType: false,
                                   processData: false,
                                   xhr: function()
                                        {
                                          var xhr = new window.XMLHttpRequest();
                                          xhr.upload.addEventListener("progress",
                                                                      uploadProgressHandler,
                                                                      false
                                                                     );
                                          xhr.addEventListener("load", loadHandler, false);
                                          xhr.addEventListener("error", errorHandler, false);
                                          xhr.addEventListener("abort", abortHandler, false);

                                          return xhr;
                                        }
                                  }
                                 );
                         }
                        );
</script>

File upload progress bar with jQuery - Stack Overflow

jquery file-upload progress-bar
Rectangle 27 1

<script type="text/javascript">
  function uploadProgressHandler(event)
  {
    $("#loaded_n_total").html("Uploaded "+event.loaded+" bytes of "+event.total);
    var percent = (event.loaded / event.total) * 100;
    var progress = Math.round(percent);
    $("#uploadProgressBar").html(progress + " percent na ang progress");
    $("#uploadProgressBar").css("width", progress + "%");
    $("#status").html(progress +"% uploaded... please wait");
  }

  function loadHandler(event)
  {
    $("#status").html(event.target.responseText);
    $("#uploadProgressBar").css("width", "0%");
  }

  function errorHandler(event){
    $("#status").html("Upload Failed");
  }

  function abortHandler(event){
    $("#status").html("Upload Aborted");
  }

  $("#uploadFile").click(function(event)
                         {
                           event.preventDefault();
                           var file = $("#fileUpload")[0].files[0];
                           var formData = new FormData();
                           formData.append("file1", file);

                           $.ajax({url: 'http://testarea.local/UploadWithProgressBar1/file_upload_parser.php',
                                   method: 'POST',
                                   type: 'POST',
                                   data: formData,
                                   contentType: false,
                                   processData: false,
                                   xhr: function()
                                        {
                                          var xhr = new window.XMLHttpRequest();
                                          xhr.upload.addEventListener("progress",
                                                                      uploadProgressHandler,
                                                                      false
                                                                     );
                                          xhr.addEventListener("load", loadHandler, false);
                                          xhr.addEventListener("error", errorHandler, false);
                                          xhr.addEventListener("abort", abortHandler, false);

                                          return xhr;
                                        }
                                  }
                                 );
                         }
                        );
</script>

File upload progress bar with jQuery - Stack Overflow

jquery file-upload progress-bar
Rectangle 27 2

<style type="text/css">
    html, body, #map_canvas {
        width:   750px;
        height:  600px;
        margin:  0;
        padding: 0;
    }
        .infowindow * {font-size: 90%; margin: 0}
    </style>

            <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
            <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
            <script type="text/javascript" src="http://geoxml3.googlecode.com/svn/branches/kmz/ZipFile.complete.js"></script>
            <script type="text/javascript" src="http://geoxml3.googlecode.com/svn/branches/kmz/geoxml3.js"></script>
            <script type="text/javascript" src="http://geoxml3.googlecode.com/svn/trunk/ProjectedOverlay.js"></script> 

    <script type="text/javascript">
                var geoXml = null;
                var geoXmlDoc = null;
                var map = null;
                var myLatLng = null;
                var myGeoXml3Zoom = true;
                var sidebarHtml = "";
                var infowindow = null;
                var kmlLayer = null;
                var filename = "test.kmz";      //kml or kmz file                   
                function MapTypeId2UrlValue(maptype) {
                    var urlValue = 'm';
                    switch (maptype) {
                        case google.maps.MapTypeId.HYBRID: urlValue = 'h';
                            break;
                        case google.maps.MapTypeId.SATELLITE: urlValue = 'k';
                            break;
                        case google.maps.MapTypeId.TERRAIN: urlValue = 't';
                            break;
                        default:
                        case google.maps.MapTypeId.ROADMAP: urlValue = 'm';
                            break;
                    }
                    return urlValue;
                }


                function initialize() {
                    myLatLng = new google.maps.LatLng(39.8000959563484, -89.549560546875);
                    // these set the initial center, zoom and maptype for the map 
                    // if it is not specified in the query string
                    var lat = 37.422104808;
                    var lng = -122.0838851;
                    var zoom = 18;
                    var maptype = google.maps.MapTypeId.ROADMAP;

                    // If there are any parameters at eh end of the URL, they will be in  location.search
                    // looking something like  "?marker=3"

                    // skip the first character, we are not interested in the "?"
                    var query = location.search.substring(1);

                    // split the rest at each "&" character to give a list of  "argname=value"  pairs
                    var pairs = query.split("&");
                    for (var i = 0; i < pairs.length; i++) {
                        // break each pair at the first "=" to obtain the argname and value
                        var pos = pairs[i].indexOf("=");
                        var argname = pairs[i].substring(0, pos).toLowerCase();
                        var value = pairs[i].substring(pos + 1).toLowerCase();

                        // process each possible argname  -  use unescape() if theres any chance of spaces
                        if (argname == "id") { id = unescape(value); }
                        if (argname == "filename") { filename = unescape(value); }
                        if (argname == "marker") { index = parseFloat(value); }
                        if (argname == "lat") { lat = parseFloat(value); }
                        if (argname == "lng") { lng = parseFloat(value); }
                        if (argname == "zoom") {
                            zoom = parseInt(value);
                            myGeoXml3Zoom = false;
                        }
                        if (argname == "type") {
                            // from the v3 documentation 8/24/2010
                            // HYBRID This map type displays a transparent layer of major streets on satellite images. 
                            // ROADMAP This map type displays a normal street map. 
                            // SATELLITE This map type displays satellite images. 
                            // TERRAIN This map type displays maps with physical features such as terrain and vegetation. 
                            if (value == "m") { maptype = google.maps.MapTypeId.ROADMAP; }
                            if (value == "k") { maptype = google.maps.MapTypeId.SATELLITE; }
                            if (value == "h") { maptype = google.maps.MapTypeId.HYBRID; }
                            if (value == "t") { maptype = google.maps.MapTypeId.TERRAIN; }

                        }
                    }
                    if (!isNaN(lat) && !isNaN(lng)) {
                        myLatLng = new google.maps.LatLng(lat, lng);
                    }
                    var myOptions = {
                        zoom: zoom,
                        center: myLatLng,
                        // zoom: 5,
                        // center: myLatlng,
                        mapTypeId: maptype
                    };
                    map = new google.maps.Map(document.getElementById("map_canvas"),
                          myOptions);
                    infowindow = new google.maps.InfoWindow({});

                    geoXml = new geoXML3.parser({
                        map: map,
                        infoWindow: infowindow,
                        singleInfoWindow: true,
                        zoom: myGeoXml3Zoom,
                        markerOptions: { optimized: false },
                        afterParse: useTheData
                    });
                    geoXml.parse(filename);

                };

                //            function kmlPgClick(pm) {
                //                if (geoXml.docs[0].placemarks[pm].polygon.getMap()) {
                //                    google.maps.event.trigger(geoXmlDoc.placemarks[pm].polygon, "click");
                //                } else {
                //                    geoXmlDoc.placemarks[pm].polygon.setMap(map);
                //                    google.maps.event.trigger(geoXmlDoc.placemarks[pm].polygon, "click");
                //                }
                //            }
                //            function kmlPlClick(pm) {
                //                if (geoXml.docs[0].placemarks[pm].polyline.getMap()) {
                //                    google.maps.event.trigger(geoXmlDoc.placemarks[pm].polyline, "click");
                //                } else {
                //                    geoXmlDoc.placemarks[pm].polyline.setMap(map);
                //                    google.maps.event.trigger(geoXmlDoc.placemarks[pm].polyline, "click");
                //                }
                //            }
                //            function kmlClick(pm) {
                //                if (geoXml.docs[0].placemarks[pm].marker.getMap()) {
                //                    google.maps.event.trigger(geoXml.docs[0].placemarks[pm].marker, "click");
                //                } else {
                //                    geoXmlDoc.placemarks[pm].marker.setMap(map);
                //                    google.maps.event.trigger(geoXmlDoc.placemarks[pm].marker, "click");
                //                }
                //            }

                function kmlColor(kmlIn) {
                    var kmlColor = {};
                    if (kmlIn) {
                        aa = kmlIn.substr(0, 2);
                        bb = kmlIn.substr(2, 2);
                        gg = kmlIn.substr(4, 2);
                        rr = kmlIn.substr(6, 2);
                        kmlColor.color = "#" + rr + gg + bb;
                        kmlColor.opacity = parseInt(aa, 16) / 256;
                    } else {
                        // defaults
                        kmlColor.color = "red";
                        kmlColor.opacity = 0.45;
                    }
                    return kmlColor;
                }
                var highlightOptions = { fillColor: "red", strokeColor: "#000000", fillOpacity: 0.9, strokeWidth: 10 };
                var highlightLineOptions = { strokeColor: "red", strokeWidth: 10 };
                function kmlHighlightPoly(pm) {
                    for (var i = 0; i < geoXmlDoc.placemarks.length; i++) {
                        var placemark = geoXmlDoc.placemarks[i];
                        if (i == pm) {
                            if (placemark.polygon) placemark.polygon.setOptions(highlightOptions);
                            if (placemark.polyline) placemark.polyline.setOptions(highlightLineOptions);
                        } else {
                            if (placemark.polygon) placemark.polygon.setOptions(placemark.polygon.normalStyle);
                            if (placemark.polyline) placemark.polyline.setOptions(placemark.polyline.normalStyle);
                        }
                    }
                }
                function kmlUnHighlightPoly(pm) {
                    for (var i = 0; i < geoXmlDoc.placemarks.length; i++) {
                        if (i == pm) {
                            var placemark = geoXmlDoc.placemarks[i];
                            if (placemark.polygon) placemark.polygon.setOptions(placemark.polygon.normalStyle);
                            if (placemark.polyline) placemark.polyline.setOptions(placemark.polyline.normalStyle);
                        }
                    }
                }
                function showAll() {
                    map.fitBounds(geoXmlDoc.bounds);
                    for (var i = 0; i < geoXmlDoc.placemarks.length; i++) {
                        var placemark = geoXmlDoc.placemarks[i];
                        if (placemark.polygon) placemark.polygon.setMap(map);
                        if (placemark.polyline) placemark.polyline.setMap(map);
                        if (placemark.marker) placemark.marker.setMap(map);
                    }
                }

                function highlightPoly(poly, polynum) {
                    //    poly.setOptions({fillColor: "#0000FF", strokeColor: "#0000FF", fillOpacity: 0.3}) ;
                    google.maps.event.addListener(poly, "mouseover", function () {
                        var rowElem = document.getElementById('row' + polynum);
                        if (rowElem) rowElem.style.backgroundColor = "red";
                        if (poly instanceof google.maps.Polygon) {
                            poly.setOptions(highlightOptions);
                        } else if (poly instanceof google.maps.Polyline) {
                            poly.setOptions(highlightLineOptions);
                        }
                    });
                    google.maps.event.addListener(poly, "mouseout", function () {
                        var rowElem = document.getElementById('row' + polynum);
                        if (rowElem) rowElem.style.backgroundColor = "red";
                        poly.setOptions(poly.normalStyle);
                    });               
                }
                function makeSidebarPolylineEntry(i) {
                    var name = geoXmlDoc.placemarks[i].name;
                    if (!name || (name.length == 0)) name = "polyline #" + i;
                    // alert(name);
                    sidebarHtml += '<tr id="row' + i + '"><td onmouseover="kmlHighlightPoly(' + i + ');" onmouseout="kmlUnHighlightPoly(' + i + ');"><a href="javascript:kmlPlClick(' + i + ');">' + name + '</a> - <a href="javascript:kmlShowPlacemark(' + i + ');">show</a></td></tr>';

                }
                function makeSidebarEntry(i) {
                    var name = geoXmlDoc.placemarks[i].name;
                    if (!name || (name.length == 0)) name = "marker #" + i;
                    // alert(name);
                    sidebarHtml += '<tr id="row' + i + '"><td><a href="javascript:kmlClick(' + i + ');">' + name + '</a></td></tr>';
                }  
                function useTheData(doc) {
                    var currentBounds = map.getBounds();
                    if (!currentBounds) currentBounds = new google.maps.LatLngBounds();
                    // Geodata handling goes here, using JSON properties of the doc object
                    sidebarHtml = '<table><tr><td><a href="javascript:showAll();">Show All</a></td></tr>';
                    //  var sidebarHtml = '<table>';
                    geoXmlDoc = doc[0];
                    for (var i = 0; i < geoXmlDoc.placemarks.length; i++) {
                        // console.log(doc[0].markers[i].title);
                        var placemark = geoXmlDoc.placemarks[i];
                        if (placemark.polygon) {
                            if (currentBounds.intersects(placemark.polygon.bounds)) {
                                //makeSidebarPolygonEntry(i);
                            }
                            var kmlStrokeColor = kmlColor(placemark.style.color);
                            var kmlFillColor = kmlColor(placemark.style.fillcolor);
                            var normalStyle = {
                                strokeColor: kmlStrokeColor.color,
                                strokeWeight: placemark.style.width,
                                strokeOpacity: kmlStrokeColor.opacity,
                                fillColor: kmlFillColor.color,
                                fillOpacity: kmlFillColor.opacity
                            };
                            placemark.polygon.normalStyle = normalStyle;

                            highlightPoly(placemark.polygon, i);
                        }
                        if (placemark.polyline) {
                            if (currentBounds.intersects(placemark.polyline.bounds)) {
                                makeSidebarPolylineEntry(i);
                            }
                            var kmlStrokeColor = kmlColor(placemark.style.color);
                            var normalStyle = {
                                strokeColor: kmlStrokeColor.color,
                                strokeWeight: placemark.style.width,
                                strokeOpacity: kmlStrokeColor.opacity
                            };
                            placemark.polyline.normalStyle = normalStyle;

                            highlightPoly(placemark.polyline, i);
                        }
                        if (placemark.marker) {
                            if (currentBounds.contains(placemark.marker.getPosition())) {
                                makeSidebarEntry(i);
                            }
                        }

                        /*    doc[0].markers[i].setVisible(false); */
                    }
                    sidebarHtml += "</table>";
                    document.getElementById("sidebar").innerHTML = sidebarHtml;         //show to all link
                };           

            </script>

I would suggest getting a local copy of geoxml3.js, Zipfile.complete.js and ProjectedOverlay.js, rather than linking to the tip of the SVN tree. Those versions may change at any time.

Tried to use this code and this only highlights the poly from the first KML file when using multiple kml files ... any suggestion?

javascript - Change the KmlLayer colour in the Google Maps - Stack Ove...

javascript google-maps styling
Rectangle 27 2

<style type="text/css">
    html, body, #map_canvas {
        width:   750px;
        height:  600px;
        margin:  0;
        padding: 0;
    }
        .infowindow * {font-size: 90%; margin: 0}
    </style>

            <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
            <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
            <script type="text/javascript" src="http://geoxml3.googlecode.com/svn/branches/kmz/ZipFile.complete.js"></script>
            <script type="text/javascript" src="http://geoxml3.googlecode.com/svn/branches/kmz/geoxml3.js"></script>
            <script type="text/javascript" src="http://geoxml3.googlecode.com/svn/trunk/ProjectedOverlay.js"></script> 

    <script type="text/javascript">
                var geoXml = null;
                var geoXmlDoc = null;
                var map = null;
                var myLatLng = null;
                var myGeoXml3Zoom = true;
                var sidebarHtml = "";
                var infowindow = null;
                var kmlLayer = null;
                var filename = "test.kmz";      //kml or kmz file                   
                function MapTypeId2UrlValue(maptype) {
                    var urlValue = 'm';
                    switch (maptype) {
                        case google.maps.MapTypeId.HYBRID: urlValue = 'h';
                            break;
                        case google.maps.MapTypeId.SATELLITE: urlValue = 'k';
                            break;
                        case google.maps.MapTypeId.TERRAIN: urlValue = 't';
                            break;
                        default:
                        case google.maps.MapTypeId.ROADMAP: urlValue = 'm';
                            break;
                    }
                    return urlValue;
                }


                function initialize() {
                    myLatLng = new google.maps.LatLng(39.8000959563484, -89.549560546875);
                    // these set the initial center, zoom and maptype for the map 
                    // if it is not specified in the query string
                    var lat = 37.422104808;
                    var lng = -122.0838851;
                    var zoom = 18;
                    var maptype = google.maps.MapTypeId.ROADMAP;

                    // If there are any parameters at eh end of the URL, they will be in  location.search
                    // looking something like  "?marker=3"

                    // skip the first character, we are not interested in the "?"
                    var query = location.search.substring(1);

                    // split the rest at each "&" character to give a list of  "argname=value"  pairs
                    var pairs = query.split("&");
                    for (var i = 0; i < pairs.length; i++) {
                        // break each pair at the first "=" to obtain the argname and value
                        var pos = pairs[i].indexOf("=");
                        var argname = pairs[i].substring(0, pos).toLowerCase();
                        var value = pairs[i].substring(pos + 1).toLowerCase();

                        // process each possible argname  -  use unescape() if theres any chance of spaces
                        if (argname == "id") { id = unescape(value); }
                        if (argname == "filename") { filename = unescape(value); }
                        if (argname == "marker") { index = parseFloat(value); }
                        if (argname == "lat") { lat = parseFloat(value); }
                        if (argname == "lng") { lng = parseFloat(value); }
                        if (argname == "zoom") {
                            zoom = parseInt(value);
                            myGeoXml3Zoom = false;
                        }
                        if (argname == "type") {
                            // from the v3 documentation 8/24/2010
                            // HYBRID This map type displays a transparent layer of major streets on satellite images. 
                            // ROADMAP This map type displays a normal street map. 
                            // SATELLITE This map type displays satellite images. 
                            // TERRAIN This map type displays maps with physical features such as terrain and vegetation. 
                            if (value == "m") { maptype = google.maps.MapTypeId.ROADMAP; }
                            if (value == "k") { maptype = google.maps.MapTypeId.SATELLITE; }
                            if (value == "h") { maptype = google.maps.MapTypeId.HYBRID; }
                            if (value == "t") { maptype = google.maps.MapTypeId.TERRAIN; }

                        }
                    }
                    if (!isNaN(lat) && !isNaN(lng)) {
                        myLatLng = new google.maps.LatLng(lat, lng);
                    }
                    var myOptions = {
                        zoom: zoom,
                        center: myLatLng,
                        // zoom: 5,
                        // center: myLatlng,
                        mapTypeId: maptype
                    };
                    map = new google.maps.Map(document.getElementById("map_canvas"),
                          myOptions);
                    infowindow = new google.maps.InfoWindow({});

                    geoXml = new geoXML3.parser({
                        map: map,
                        infoWindow: infowindow,
                        singleInfoWindow: true,
                        zoom: myGeoXml3Zoom,
                        markerOptions: { optimized: false },
                        afterParse: useTheData
                    });
                    geoXml.parse(filename);

                };

                //            function kmlPgClick(pm) {
                //                if (geoXml.docs[0].placemarks[pm].polygon.getMap()) {
                //                    google.maps.event.trigger(geoXmlDoc.placemarks[pm].polygon, "click");
                //                } else {
                //                    geoXmlDoc.placemarks[pm].polygon.setMap(map);
                //                    google.maps.event.trigger(geoXmlDoc.placemarks[pm].polygon, "click");
                //                }
                //            }
                //            function kmlPlClick(pm) {
                //                if (geoXml.docs[0].placemarks[pm].polyline.getMap()) {
                //                    google.maps.event.trigger(geoXmlDoc.placemarks[pm].polyline, "click");
                //                } else {
                //                    geoXmlDoc.placemarks[pm].polyline.setMap(map);
                //                    google.maps.event.trigger(geoXmlDoc.placemarks[pm].polyline, "click");
                //                }
                //            }
                //            function kmlClick(pm) {
                //                if (geoXml.docs[0].placemarks[pm].marker.getMap()) {
                //                    google.maps.event.trigger(geoXml.docs[0].placemarks[pm].marker, "click");
                //                } else {
                //                    geoXmlDoc.placemarks[pm].marker.setMap(map);
                //                    google.maps.event.trigger(geoXmlDoc.placemarks[pm].marker, "click");
                //                }
                //            }

                function kmlColor(kmlIn) {
                    var kmlColor = {};
                    if (kmlIn) {
                        aa = kmlIn.substr(0, 2);
                        bb = kmlIn.substr(2, 2);
                        gg = kmlIn.substr(4, 2);
                        rr = kmlIn.substr(6, 2);
                        kmlColor.color = "#" + rr + gg + bb;
                        kmlColor.opacity = parseInt(aa, 16) / 256;
                    } else {
                        // defaults
                        kmlColor.color = "red";
                        kmlColor.opacity = 0.45;
                    }
                    return kmlColor;
                }
                var highlightOptions = { fillColor: "red", strokeColor: "#000000", fillOpacity: 0.9, strokeWidth: 10 };
                var highlightLineOptions = { strokeColor: "red", strokeWidth: 10 };
                function kmlHighlightPoly(pm) {
                    for (var i = 0; i < geoXmlDoc.placemarks.length; i++) {
                        var placemark = geoXmlDoc.placemarks[i];
                        if (i == pm) {
                            if (placemark.polygon) placemark.polygon.setOptions(highlightOptions);
                            if (placemark.polyline) placemark.polyline.setOptions(highlightLineOptions);
                        } else {
                            if (placemark.polygon) placemark.polygon.setOptions(placemark.polygon.normalStyle);
                            if (placemark.polyline) placemark.polyline.setOptions(placemark.polyline.normalStyle);
                        }
                    }
                }
                function kmlUnHighlightPoly(pm) {
                    for (var i = 0; i < geoXmlDoc.placemarks.length; i++) {
                        if (i == pm) {
                            var placemark = geoXmlDoc.placemarks[i];
                            if (placemark.polygon) placemark.polygon.setOptions(placemark.polygon.normalStyle);
                            if (placemark.polyline) placemark.polyline.setOptions(placemark.polyline.normalStyle);
                        }
                    }
                }
                function showAll() {
                    map.fitBounds(geoXmlDoc.bounds);
                    for (var i = 0; i < geoXmlDoc.placemarks.length; i++) {
                        var placemark = geoXmlDoc.placemarks[i];
                        if (placemark.polygon) placemark.polygon.setMap(map);
                        if (placemark.polyline) placemark.polyline.setMap(map);
                        if (placemark.marker) placemark.marker.setMap(map);
                    }
                }

                function highlightPoly(poly, polynum) {
                    //    poly.setOptions({fillColor: "#0000FF", strokeColor: "#0000FF", fillOpacity: 0.3}) ;
                    google.maps.event.addListener(poly, "mouseover", function () {
                        var rowElem = document.getElementById('row' + polynum);
                        if (rowElem) rowElem.style.backgroundColor = "red";
                        if (poly instanceof google.maps.Polygon) {
                            poly.setOptions(highlightOptions);
                        } else if (poly instanceof google.maps.Polyline) {
                            poly.setOptions(highlightLineOptions);
                        }
                    });
                    google.maps.event.addListener(poly, "mouseout", function () {
                        var rowElem = document.getElementById('row' + polynum);
                        if (rowElem) rowElem.style.backgroundColor = "red";
                        poly.setOptions(poly.normalStyle);
                    });               
                }
                function makeSidebarPolylineEntry(i) {
                    var name = geoXmlDoc.placemarks[i].name;
                    if (!name || (name.length == 0)) name = "polyline #" + i;
                    // alert(name);
                    sidebarHtml += '<tr id="row' + i + '"><td onmouseover="kmlHighlightPoly(' + i + ');" onmouseout="kmlUnHighlightPoly(' + i + ');"><a href="javascript:kmlPlClick(' + i + ');">' + name + '</a> - <a href="javascript:kmlShowPlacemark(' + i + ');">show</a></td></tr>';

                }
                function makeSidebarEntry(i) {
                    var name = geoXmlDoc.placemarks[i].name;
                    if (!name || (name.length == 0)) name = "marker #" + i;
                    // alert(name);
                    sidebarHtml += '<tr id="row' + i + '"><td><a href="javascript:kmlClick(' + i + ');">' + name + '</a></td></tr>';
                }  
                function useTheData(doc) {
                    var currentBounds = map.getBounds();
                    if (!currentBounds) currentBounds = new google.maps.LatLngBounds();
                    // Geodata handling goes here, using JSON properties of the doc object
                    sidebarHtml = '<table><tr><td><a href="javascript:showAll();">Show All</a></td></tr>';
                    //  var sidebarHtml = '<table>';
                    geoXmlDoc = doc[0];
                    for (var i = 0; i < geoXmlDoc.placemarks.length; i++) {
                        // console.log(doc[0].markers[i].title);
                        var placemark = geoXmlDoc.placemarks[i];
                        if (placemark.polygon) {
                            if (currentBounds.intersects(placemark.polygon.bounds)) {
                                //makeSidebarPolygonEntry(i);
                            }
                            var kmlStrokeColor = kmlColor(placemark.style.color);
                            var kmlFillColor = kmlColor(placemark.style.fillcolor);
                            var normalStyle = {
                                strokeColor: kmlStrokeColor.color,
                                strokeWeight: placemark.style.width,
                                strokeOpacity: kmlStrokeColor.opacity,
                                fillColor: kmlFillColor.color,
                                fillOpacity: kmlFillColor.opacity
                            };
                            placemark.polygon.normalStyle = normalStyle;

                            highlightPoly(placemark.polygon, i);
                        }
                        if (placemark.polyline) {
                            if (currentBounds.intersects(placemark.polyline.bounds)) {
                                makeSidebarPolylineEntry(i);
                            }
                            var kmlStrokeColor = kmlColor(placemark.style.color);
                            var normalStyle = {
                                strokeColor: kmlStrokeColor.color,
                                strokeWeight: placemark.style.width,
                                strokeOpacity: kmlStrokeColor.opacity
                            };
                            placemark.polyline.normalStyle = normalStyle;

                            highlightPoly(placemark.polyline, i);
                        }
                        if (placemark.marker) {
                            if (currentBounds.contains(placemark.marker.getPosition())) {
                                makeSidebarEntry(i);
                            }
                        }

                        /*    doc[0].markers[i].setVisible(false); */
                    }
                    sidebarHtml += "</table>";
                    document.getElementById("sidebar").innerHTML = sidebarHtml;         //show to all link
                };           

            </script>

I would suggest getting a local copy of geoxml3.js, Zipfile.complete.js and ProjectedOverlay.js, rather than linking to the tip of the SVN tree. Those versions may change at any time.

Tried to use this code and this only highlights the poly from the first KML file when using multiple kml files ... any suggestion?

javascript - Change the KmlLayer colour in the Google Maps - Stack Ove...

javascript google-maps styling
Rectangle 27 0

This library has an option of image_markup, documentation, using that will avoid javascript solutions.

Add a link with target="_blank" within the image_markup option when you instance prettyPhoto

image_markup: '<a href="{path}" target="_blank"><img id="fullResImage" src="{path}" /></a>'
$("a[rel^='prettyPhoto']").prettyPhoto({image_markup: '<a href="{path}" target="_blank"><img id="fullResImage" src="{path}" /></a>'});

Otherwise, you'd have to do something like this, jsFiddle Example

$(document.body).on('click', '#fullResImage', function(){
    window.open(this.src, '_blank');
});

javascript - Using jquery to have image when clicked link to URL in ne...

javascript jquery
Rectangle 27 0

You can do this:

$(".btn").click(function(){
    var url = window.location.href.replace(/http/, 'https');
    window.location.href = url;
});

I'd anchor the protocol regex to the start of the string, otherwise it is possible to have some unintended side-effects ;-).

javascript - How to prepend a https to url on click - jquery - Stack O...

javascript jquery
Rectangle 27 0

smartass anwser: use a button.

alternative: you must make sure to trigger the preventDefault in youre jQuery event handler

$("dosomthing").click(function(e){
  //make magic happen
  e.preventDefault()
})

this works on html forms thats submitting and such.

it is best pratice to only use a tags for link (somthing that changes the url) and buttons for other sorts of interactions.

search bots and other web crawlers expect a tags to link to a other html document (hyperlink) and up to and including html 4. or to a other point in the current document.

javascript - Prevent a standard a href/jquery click combo from appendi...

javascript jquery hyperlink
Rectangle 27 0

We use the window.location.hash to handle the history in our app. I guess it works well in single page apps and is very simple.

For multiple pages app, I don't think it's a good idea to try to control and change the natural page history of the browser.

When the user clicks "back" or "next", the hash key gets the previous or next value. Because of IE7 you need to use a polling technique (but it is ok in all browsers), with a setInterval(...) and a fast function that checks for instance every 300ms if the hash has changed.

Then, if a change occurs, act accordingly. ie: call the server and refresh some areas in the page.

It works very well, and does not kill at all the responsiveness of the application.

In Javascript, perferably JQuery, how do I add something to the URL wh...

javascript jquery browser
Rectangle 27 0

I'd suggest using a cross browser library such as jQuery rather than straight JavaScript. With jQuery, you'd add a click handler for your button, grab the value of the input, build your URL, and set window.location to go to the new url

<input type="text" id="q" />
<input type="button" id="submit" value="submit" />
$(function () {
    $('#submit').click(function() {
        var url = "http://www.google.com/search?q=";
        url += $('#q').val();
        window.location = url;
    });
});

@Craig -- also try to use form.submit not input.click ... or else the form will be submitted.

There's a very good reason to use jQuery. As his application grows, he'll undoubtedly get to the point where he needs to write some code that performs differently cross browser. Start with jQuery (or Zepto if jQuery is too big for your taste) and you don't have a mishmash of native DOM manipulation code mixed in with jQuery code. There's no reason to create a form as in your example. You've just created excessive markup.

I don't feel jQuery is a bad solution here. It's easy to use for newbies, as this guy likely is, and it's cross browser compatible. Basically substitute any modern dom manipulating library and do something similar. I don't see any need to submit the value unless they want to store that data. Therefore I don't really see a need for a form or submit button here. A simple button and some script should accomplish the task/

javascript - Is it possible to update a url link based on user text in...

javascript html url input keyword
Rectangle 27 0

The answers suggested here are valid, but...

Be extremely careful when using the window.location.hash as it is in a jQuery selector because this could lead to a XSS vulnerability. $() can also create an HTML element and with a carefully constructed hash value, someone could execute arbitrary JavaScript code.

http://my-website.com/about#'><img src=x onerror=alert(/XSSed/)>

If my-websites.com/about page uses the window.location.hash inside a jQuery selector, that onerror code would end up getting executed.

jQuery if url hash, click event/activate javascript - Stack Overflow

javascript jquery url
Rectangle 27 0

You should use the beforeUnload event of the window instance returned by the window.open() call, like this:

popup = window.open('relative_url', 'popup');
$(popup).bind('beforeunload', function() {
    disableShadow();
});

Note that the URL must be on the same domain in order for the opener window to interact with the popup!

javascript - How can popup a window in a new URL but also shadow out t...

javascript jquery