Jump to content

JS File Issues - can't retrieve image


aw.be
 Share

Recommended Posts

Hello everyone.

I'm still a noob but I'm learning. I'm really a noob with javascript but it's coming along. With the help of a tutorial, I have an image (called in javascript) at the bottom of the page that returns to the top of the page. It works in the local (static) version of the site.

This is in my footer include file:

<script type="text/javascript" src="<?php echo $config->urls->templates?>js/plugins.js?v=1"></script>

<script type="text/javascript" src="<?php echo $config->urls->templates?>js/script.js"></script>

Can anyone see where I've made a simple, glaring error? Or is this a bigger issue to try to solve?

Thanks.

Aaron

Link to comment
Share on other sites

Thanks SiNNuT.

This is the image path declaration -

.scrollUp({location:"right",image_src:"img/arrow_up.png",wait:100,time:300});

At least I think that's it - like I said, I'm very very new to JS.

Link to comment
Share on other sites

Come to think of it, i'm not sure how js handles paths. In CSS paths are handled relative to the css file itself. Simple.

In js url's are relative to the resource that calls it? Dunno, maybe you should use a root relative or even absolute path/url.

How do most js users do this?

Link to comment
Share on other sites

I think that URLs will be relative to the requested URL? So if the JS is loaded on page /contact-us/ then the code snippet above would be looking for /contact-us/img/arrow_up.png, which would be incorrect. One way you can get around this is to let PW populate them for you. In your document <head>, add this before any other <script> calls:

<script>
var rootUrl = '<?=$config->urls->root?>'; 
var templatesUrl = '<?=$config->urls->templates?>'; 
</script>

Then you'd be able to do this:

.scrollUp({location:"right",image_src: templatesUrl + "js/img/arrow_up.png",wait:100,time:300});
  • Like 3
Link to comment
Share on other sites

This is about javascript rather than PW, so don't have tutorials about this specifically. I think what I mentioned should work, but it's just a matter of debugging to find out why it's not working. Where I would start is to just get it working with hard-coded URLs. Meaning, if your arrow-up.png file is in /site/templates/scripts/js/img/arrow-up.png, then hard code that location and see if it starts working:

.scrollUp({location:"right",image_src: "/site/templates/scripts/js/img/arrow_up.png",wait:100,time:300});

Also make sure you have a javascript console open (like in Chrome: View > Developer > Javascript Console), as it's nearly impossible to debug this kind of stuff without a console to tell you when an error occurs.

  • Like 1
Link to comment
Share on other sites

  • 3 years later...
On 12/10/2012 at 7:59 PM, ryan said:

I think that URLs will be relative to the requested URL? So if the JS is loaded on page /contact-us/ then the code snippet above would be looking for /contact-us/img/arrow_up.png, which would be incorrect. One way you can get around this is to let PW populate them for you. In your document <head>, add this before any other <script> calls:


<script>
var rootUrl = '<?=$config->urls->root?>'; 
var templatesUrl = '<?=$config->urls->templates?>'; 
</script>
 

Then you'd be able to do this:


.scrollUp({location:"right",image_src: templatesUrl + "js/img/arrow_up.png",wait:100,time:300});
 

Ok, so I know this is pretty old. However, I just bumped into this exact issue helping my stepson make his own website. It was a wordpress theme and I thought it would be a good idea (for both of us to learn something) and change this static site into a dynamic PW one! So we got to work, everything ran quite smooth apart from the backstretch jQuery plugin and image paths:

http://srobbin.com/jquery-plugins/backstretch/

This is called in main.js:

$(".image-background").backstretch("images/image-bg.jpg");

...so Ryans' suggestion worked as follows:

$(".image-background").backstretch(templatesURL + "images/image-bg.jpg");

..and the class is on the actual PW page like this:

//main.php
<head>
<!-- stuff -->
	<script>
		var templatesUrl = '<?php echo $config->urls->templates ?>'; 
	</script>
</head>

<body class="image-background">
	<!-- stuff here -->
  	<script type="text/rocketscript" data-rocketsrc="js/main.js"></script>
</body>

...so now on every page the background image works as expected. Previously it worked only on the homepage, I presume js paths are relative to where the script is called rather from the files location.

I used unminify here for the entire file which I can share. Neither of us wrote this and I have no idea what most of it even does, it was included in the theme, but you can see where this is called (about 4 blocks in):

// main.js
(function($) {
    "use strict";
    if (navigator.userAgent.match(/IEMobile\/10\.0/)) {
        var msViewportStyle = document.createElement("style");
        msViewportStyle.appendChild(document.createTextNode("@-ms-viewport{width:auto!important}"));
        document.getElementsByTagName("head")[0].appendChild(msViewportStyle);
    }
    $(function() {
        var nua = navigator.userAgent
        var isAndroid = (nua.indexOf('Mozilla/5.0') > -1 && nua.indexOf('Android ') > -1 && nua.indexOf('AppleWebKit') > -1 && nua.indexOf('Chrome') === -1)
        if (isAndroid) {
            $('select.form-control').removeClass('form-control').css('width', '100%')
        }
    })
    $(window).load(function() {
        var preloaderDelay = 350,
            preloaderFadeOutTime = 800;

        function hidePreloader() {
            var loadingAnimation = $('#loading-animation'),
                preloader = $('#preloader');
            loadingAnimation.fadeOut();
            preloader.delay(preloaderDelay).fadeOut(preloaderFadeOutTime);
        }
        hidePreloader();
    });
    $(".image-background").backstretch("images/image-bg.jpg");
    if ($('body').hasClass('parallax-background')) {
        $.parallaxify({
            positionProperty: 'transform',
            responsive: true,
            motionType: 'natural',
            mouseMotionType: 'performance',
            motionAngleX: 70,
            motionAngleY: 70,
            alphaFilter: 0.5,
            adjustBasePosition: true,
            alphaPosition: 0.025,
        });
    }
    $(".particle-background").backstretch("../../assets/images/bg/particle-bg.jpg");
    $('.particles').particleground({
        dotColor: '#5cbdaa',
        lineColor: '#5cbdaa',
        parallax: false,
    });
    $(".snowdrops-background").backstretch("../../assets/images/bg/snowdrops-bg.jpg");
    $(".video-background").backstretch("../../assets/video/Storm_darck.jpg");
    $(".player").each(function() {
        $(".player").mb_YTPlayer();
    });
    $('#clock-countdown').countdown('2018/12/30 12:00:00').on('update.countdown', function(event) {
        var $this = $(this).html(event.strftime('' + '<div class="counter-container"><div class="counter-box first"><div class="number">%-D</div><span>Day%!d</span></div>' + '<div class="counter-box"><div class="number">%H</div><span>Hours</span></div>' + '<div class="counter-box"><div class="number">%M</div><span>Minutes</span></div>' + '<div class="counter-box last"><div class="number">%S</div><span>Seconds</span></div></div>'));
    });
    $('.flexslider').flexslider({
        animation: "fade",
        animationLoop: true,
        slideshowSpeed: 7000,
        animationSpeed: 600,
        controlNav: false,
        directionNav: false,
        keyboard: false,
        start: function(slider) {
            $('body').removeClass('loading');
        }
    });
    $(document).ready(function() {
        $("#owl-demo").owlCarousel({
            autoPlay: 3000,
            items: 4,
            itemsDesktop: [1199, 3],
            itemsDesktopSmall: [979, 3]
        });
    });
    $("html").niceScroll({
        cursorcolor: '#ccc',
        cursoropacitymin: '0',
        cursoropacitymax: '1',
        cursorwidth: '3px',
        zindex: 10000,
        horizrailenabled: false,
    });
    $('.animated').appear(function() {
        var element = $(this),
            animation = element.data('animation'),
            animationDelay = element.data('animation-delay');
        if (animationDelay) {
            setTimeout(function() {
                element.addClass(animation + " visible");
            }, animationDelay);
        } else {
            element.addClass(animation + " visible");
        }
    });

    function initContactForm() {
        var scrollElement = $('html,body'),
            contactForm = $('.contact-form'),
            form_msg_timeout;
        contactForm.on('submit', function() {
            var requiredFields = $(this).find('.required'),
                formData = contactForm.serialize(),
                formAction = $(this).attr('action'),
                formSubmitMessage = $('.response-message');
            requiredFields.each(function() {
                if ($(this).val() == "") {
                    $(this).addClass('input-error');
                } else {
                    $(this).removeClass('input-error');
                }
            });

            function validateEmail(email) {
                var exp = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
                return exp.test(email);
            }
            var emailField = $('.contact-form-email');
            if (!validateEmail(emailField.val())) {
                emailField.addClass("input-error");
            }
            if ($(".contact-form :input").hasClass("input-error")) {
                return false;
            } else {
                clearTimeout(form_msg_timeout);
                $.post(formAction, formData, function(data) {
                    formSubmitMessage.text(data);
                    requiredFields.val("");
                    form_msg_timeout = setTimeout(function() {
                        formSubmitMessage.slideUp();
                    }, 5000);
                });
            }
            return false;
        });
    }
    initContactForm();
})(jQuery);

Anyway, I am relatively new to javascript but how would you go about making this variable (var templatesUrl) available to main.js without plonking it on the global object? I haven't actually got to jQuery yet, still on vanilla javascript (currently on closures, apply, call and bind), but thought I'd better get a decent grip on that first. I tried putting '<?php echo $config->urls->templates ?>' straight into the main.js but it didn't work. Part of me says "of course not, that's php in a js file", but the other part of me says, "but it works within the script tag didn't it?!". Clueless. Any help is most appreciated. Thanks.

Link to comment
Share on other sites

i usually do this in the head - you will need to echo these directly on the php output, because your .js files won't be processed server-side.

<script> var site = {
    "urls": {
        "templates": <?=$config->urls->templates?>,
        "root": <?=$config->urls->root?>
    }
}</script>

then you can do site.urls.templates for your var inside your main.js

  • Like 2
Link to comment
Share on other sites

7 hours ago, Macrura said:

i usually do this in the head - you will need to echo these directly on the php output, because your .js files won't be processed server-side.


<script> var site = {
    "urls": {
        "templates": <?=$config->urls->templates?>,
        "root": <?=$config->urls->root?>
    }
}</script>

then you can do site.urls.templates for your var inside your main.js

Thanks, makes sense.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...