Jquery - If width less than 767 then change href

Fruxelot picture Fruxelot · Apr 17, 2012 · Viewed 25.2k times · Source

I am currently developing a responsive website. I've developed a jquery script that changes the href attribute in a link.

$("a.modal").attr("href", "https://secured.sirvoy.com/book.php?c_id=1602&h=ea3a7c9286f068fb6c1462fad233a5e0")

Its working all fine - but i want it only to target devices that has a lesser screen width than 767 pixels (mobile devices).

this script should work but i cant really get it to work.

<script type="text/javascript">
$(document).ready(function(){
if ($(window).width() < 767) {
$("a.modal").attr("href", "https://secured.sirvoy.com/book.php?c_id=1602&h=ea3a7c9286f068fb6c1462fad233a5e0")
}
});
</script>

Link to the webpage.

http://visbyfangelse.se.linweb63.kontrollpanelen.se/rum-priser/

Its the link for the pink buttons i want to change.

Answer

John Green picture John Green · Apr 17, 2012

The problem lies in the rest of your code, actually. Shame on you for making me dig for it. :P

$('a[name=modal]').click(function(e) {
    //Cancel the link behavior
    e.preventDefault();
    // etc etc.

So, you prevent the href from firing because of preventDefault. Why not just patch your check in here:

$('a[name=modal]').click(function(e) {
    //Cancel the link behavior
    e.preventDefault();
    if ($(window).width() < 767)
    {
        // I'm assuming you'd get this dynamically somehow;
        location.href="https://secured.sirvoy.com/book.php?c_id=1602&h=ea3a7c9286f068fb6c1462fad233a5e0";
        return;
    }
    // etc etc.

Added | Full text of function to help OP make his project work:

$('a[name=modal]').click(function(e) {
    //Cancel the link behavior

    e.preventDefault();
    if ($(window).width() < 767)
    {
        // I'm assuming you'd get this dynamically somehow;
        location.href="https://secured.sirvoy.com/book.php?c_id=1602&h=ea3a7c9286f068fb6c1462fad233a5e0";
        return;
    }
    //Get the A tag
    var id = $(this).attr('href');

    //Get the screen height and width
    var maskHeight = $(document).height();
    var maskWidth = $(window).width();

    //Set height and width to mask to fill up the whole screen
    $('#mask').css({'width':maskWidth,'height':maskHeight});

    //transition effect     
    $('#mask').fadeIn(1000);    
    $('#mask').fadeTo("slow",0.8);  

    //Get the window height and width
    var winH = $(window).height();
    var winW = $(window).width();


    //transition effect
    $(id).fadeIn(2000); 

});