Laravel returning wrong response - laravel
In my Controller I have the following code:
if (isset($request->validator) && $request->validator->fails())
{
$a =
[
"error_code" => 500,
"msg" => 'The given data was invalid.',
"errors" => $request->validator->errors()
];
$a = implode(" ",$a);
return back()->setStatusCode(422)->withErrors($request->validator->errors());
}
Basically, if the request form data was invalid, it is supposed to
Send a htpp status code of 422
Send the errors itemised
But the problem is that it is only obeying the first rule(about the htpp code) but not the second.
Ie it returns this:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta http-equiv="refresh" content="0;url=http://localhost:8000/dashboard/posts/create/?type=image" />
<title>Redirecting to http://localhost:8000/dashboard/posts/create/?type=image</title>
</head>
<body>
Redirecting to http://localhost:8000/dashboard/posts/create/?type=image.
<link rel='stylesheet' type='text/css' property='stylesheet' href='//localhost:8000/_debugbar/assets/stylesheets?v=1561562319'><script type='text/javascript' src='//localhost:8000/_debugbar/assets/javascript?v=1561562319'></script><script type="text/javascript">jQuery.noConflict(true);</script>
<script> Sfdump = window.Sfdump || (function (doc) { var refStyle = doc.createElement('style'), rxEsc = /([.*+?^${}()|\[\]\/\\])/g, idRx = /\bsf-dump-\d+-ref[012]\w+\b/, keyHint = 0 <= navigator.platform.toUpperCase().indexOf('MAC') ? 'Cmd' : 'Ctrl', addEventListener = function (e, n, cb) { e.addEventListener(n, cb, false); }; (doc.documentElement.firstElementChild || doc.documentElement.children[0]).appendChild(refStyle); if (!doc.addEventListener) { addEventListener = function (element, eventName, callback) { element.attachEvent('on' + eventName, function (e) { e.preventDefault = function () {e.returnValue = false;}; e.target = e.srcElement; callback(e); }); }; } function toggle(a, recursive) { var s = a.nextSibling || {}, oldClass = s.className, arrow, newClass; if (/\bsf-dump-compact\b/.test(oldClass)) { arrow = '▼'; newClass = 'sf-dump-expanded'; } else if (/\bsf-dump-expanded\b/.test(oldClass)) { arrow = '▶'; newClass = 'sf-dump-compact'; } else { return false; } if (doc.createEvent && s.dispatchEvent) { var event = doc.createEvent('Event'); event.initEvent('sf-dump-expanded' === newClass ? 'sfbeforedumpexpand' : 'sfbeforedumpcollapse', true, false); s.dispatchEvent(event); } a.lastChild.innerHTML = arrow; s.className = s.className.replace(/\bsf-dump-(compact|expanded)\b/, newClass); if (recursive) { try { a = s.querySelectorAll('.'+oldClass); for (s = 0; s < a.length; ++s) { if (-1 == a[s].className.indexOf(newClass)) { a[s].className = newClass; a[s].previousSibling.lastChild.innerHTML = arrow; } } } catch (e) { } } return true; }; function collapse(a, recursive) { var s = a.nextSibling || {}, oldClass = s.className; if (/\bsf-dump-expanded\b/.test(oldClass)) { toggle(a, recursive); return true; } return false; }; function expand(a, recursive) { var s = a.nextSibling || {}, oldClass = s.className; if (/\bsf-dump-compact\b/.test(oldClass)) { toggle(a, recursive); return true; } return false; }; function collapseAll(root) { var a = root.querySelector('a.sf-dump-toggle'); if (a) { collapse(a, true); expand(a); return true; } return false; } function reveal(node) { var previous, parents = []; while ((node = node.parentNode || {}) && (previous = node.previousSibling) && 'A' === previous.tagName) { parents.push(previous); } if (0 !== parents.length) { parents.forEach(function (parent) { expand(parent); }); return true; } return false; } function highlight(root, activeNode, nodes) { resetHighlightedNodes(root); Array.from(nodes||[]).forEach(function (node) { if (!/\bsf-dump-highlight\b/.test(node.className)) { node.className = node.className + ' sf-dump-highlight'; } }); if (!/\bsf-dump-highlight-active\b/.test(activeNode.className)) { activeNode.className = activeNode.className + ' sf-dump-highlight-active'; } } function resetHighlightedNodes(root) { Array.from(root.querySelectorAll('.sf-dump-str, .sf-dump-key, .sf-dump-public, .sf-dump-protected, .sf-dump-private')).forEach(function (strNode) { strNode.className = strNode.className.replace(/\bsf-dump-highlight\b/, ''); strNode.className = strNode.className.replace(/\bsf-dump-highlight-active\b/, ''); }); } return function (root, x) { root = doc.getElementById(root); var indentRx = new RegExp('^('+(root.getAttribute('data-indent-pad') || ' ').replace(rxEsc, '\\$1')+')+', 'm'), options = {"maxDepth":1,"maxStringLength":160,"fileLinkFormat":false}, elt = root.getElementsByTagName('A'), len = elt.length, i = 0, s, h, t = []; while (i < len) t.push(elt[i++]); for (i in x) { options[i] = x[i]; } function a(e, f) { addEventListener(root, e, function (e) { if ('A' == e.target.tagName) { f(e.target, e); } else if ('A' == e.target.parentNode.tagName) { f(e.target.parentNode, e); } else if (e.target.nextElementSibling && 'A' == e.target.nextElementSibling.tagName) { f(e.target.nextElementSibling, e, true); } }); }; function isCtrlKey(e) { return e.ctrlKey || e.metaKey; } function xpathString(str) { var parts = str.match(/[^'"]+|['"]/g).map(function (part) { if ("'" == part) { return '"\'"'; } if ('"' == part) { return "'\"'"; } return "'" + part + "'"; }); return "concat(" + parts.join(",") + ", '')"; } function xpathHasClass(className) { return "contains(concat(' ', normalize-space(#class), ' '), ' " + className +" ')"; } addEventListener(root, 'mouseover', function (e) { if ('' != refStyle.innerHTML) { refStyle.innerHTML = ''; } }); a('mouseover', function (a, e, c) { if (c) { e.target.style.cursor = "pointer"; } else if (a = idRx.exec(a.className)) { try { refStyle.innerHTML = '.phpdebugbar pre.sf-dump .'+a[0]+'{background-color: #B729D9; color: #FFF !important; border-radius: 2px}'; } catch (e) { } } }); a('click', function (a, e, c) { if (/\bsf-dump-toggle\b/.test(a.className)) { e.preventDefault(); if (!toggle(a, isCtrlKey(e))) { var r = doc.getElementById(a.getAttribute('href').substr(1)), s = r.previousSibling, f = r.parentNode, t = a.parentNode; t.replaceChild(r, a); f.replaceChild(a, s); t.insertBefore(s, r); f = f.firstChild.nodeValue.match(indentRx); t = t.firstChild.nodeValue.match(indentRx); if (f && t && f[0] !== t[0]) { r.innerHTML = r.innerHTML.replace(new RegExp('^'+f[0].replace(rxEsc, '\\$1'), 'mg'), t[0]); } if (/\bsf-dump-compact\b/.test(r.className)) { toggle(s, isCtrlKey(e)); } } if (c) { } else if (doc.getSelection) { try { doc.getSelection().removeAllRanges(); } catch (e) { doc.getSelection().empty(); } } else { doc.selection.empty(); } } else if (/\bsf-dump-str-toggle\b/.test(a.className)) { e.preventDefault(); e = a.parentNode.parentNode; e.className = e.className.replace(/\bsf-dump-str-(expand|collapse)\b/, a.parentNode.className); } }); elt = root.getElementsByTagName('SAMP'); len = elt.length; i = 0; while (i < len) t.push(elt[i++]); len = t.length; for (i = 0; i < len; ++i) { elt = t[i]; if ('SAMP' == elt.tagName) { a = elt.previousSibling || {}; if ('A' != a.tagName) { a = doc.createElement('A'); a.className = 'sf-dump-ref'; elt.parentNode.insertBefore(a, elt); } else { a.innerHTML += ' '; } a.title = (a.title ? a.title+'\n[' : '[')+keyHint+'+click] Expand all children'; a.innerHTML += '<span>▼</span>'; a.className += ' sf-dump-toggle'; x = 1; if ('sf-dump' != elt.parentNode.className) { x += elt.parentNode.getAttribute('data-depth')/1; } elt.setAttribute('data-depth', x); var className = elt.className; elt.className = 'sf-dump-expanded'; if (className ? 'sf-dump-expanded' !== className : (x > options.maxDepth)) { toggle(a); } } else if (/\bsf-dump-ref\b/.test(elt.className) && (a = elt.getAttribute('href'))) { a = a.substr(1); elt.className += ' '+a; if (/[\[{]$/.test(elt.previousSibling.nodeValue)) { a = a != elt.nextSibling.id && doc.getElementById(a); try { s = a.nextSibling; elt.appendChild(a); s.parentNode.insertBefore(a, s); if (/^[##]/.test(elt.innerHTML)) { elt.innerHTML += ' <span>▶</span>'; } else { elt.innerHTML = '<span>▶</span>'; elt.className = 'sf-dump-ref'; } elt.className += ' sf-dump-toggle'; } catch (e) { if ('&' == elt.innerHTML.charAt(0)) { elt.innerHTML = '…'; elt.className = 'sf-dump-ref'; } } } } } if (doc.evaluate && Array.from && root.children.length > 1) { root.setAttribute('tabindex', 0); SearchState = function () { this.nodes = []; this.idx = 0; }; SearchState.prototype = { next: function () { if (this.isEmpty()) { return this.current(); } this.idx = this.idx < (this.nodes.length - 1) ? this.idx + 1 : 0; return this.current(); }, previous: function () { if (this.isEmpty()) { return this.current(); } this.idx = this.idx > 0 ? this.idx - 1 : (this.nodes.length - 1); return this.current(); }, isEmpty: function () { return 0 === this.count(); }, current: function () { if (this.isEmpty()) { return null; } return this.nodes[this.idx]; }, reset: function () { this.nodes = []; this.idx = 0; }, count: function () { return this.nodes.length; }, }; function showCurrent(state) { var currentNode = state.current(), currentRect, searchRect; if (currentNode) { reveal(currentNode); highlight(root, currentNode, state.nodes); if ('scrollIntoView' in currentNode) { currentNode.scrollIntoView(true); currentRect = currentNode.getBoundingClientRect(); searchRect = search.getBoundingClientRect(); if (currentRect.top < (searchRect.top + searchRect.height)) { window.scrollBy(0, -(searchRect.top + searchRect.height + 5)); } } } counter.textContent = (state.isEmpty() ? 0 : state.idx + 1) + ' of ' + state.count(); } var search = doc.createElement('div'); search.className = 'sf-dump-search-wrapper sf-dump-search-hidden'; search.innerHTML = ' <input type="text" class="sf-dump-search-input"> <span class="sf-dump-search-count">0 of 0<\/span> <button type="button" class="sf-dump-search-input-previous" tabindex="-1"> <svg viewBox="0 0 1792 1792" xmlns="http://www.w3.org/2000/svg"><path d="M1683 1331l-166 165q-19 19-45 19t-45-19L896 965l-531 531q-19 19-45 19t-45-19l-166-165q-19-19-19-45.5t19-45.5l742-741q19-19 45-19t45 19l742 741q19 19 19 45.5t-19 45.5z"\/><\/svg> <\/button> <button type="button" class="sf-dump-search-input-next" tabindex="-1"> <svg viewBox="0 0 1792 1792" xmlns="http://www.w3.org/2000/svg"><path d="M1683 808l-742 741q-19 19-45 19t-45-19L109 808q-19-19-19-45.5t19-45.5l166-165q19-19 45-19t45 19l531 531 531-531q19-19 45-19t45 19l166 165q19 19 19 45.5t-19 45.5z"\/><\/svg> <\/button> '; root.insertBefore(search, root.firstChild); var state = new SearchState(); var searchInput = search.querySelector('.sf-dump-search-input'); var counter = search.querySelector('.sf-dump-search-count'); var searchInputTimer = 0; var previousSearchQuery = ''; addEventListener(searchInput, 'keyup', function (e) { var searchQuery = e.target.value; /* Don't perform anything if the pressed key didn't change the query */ if (searchQuery === previousSearchQuery) { return; } previousSearchQuery = searchQuery; clearTimeout(searchInputTimer); searchInputTimer = setTimeout(function () { state.reset(); collapseAll(root); resetHighlightedNodes(root); if ('' === searchQuery) { counter.textContent = '0 of 0'; return; } var classMatches = [ "sf-dump-str", "sf-dump-key", "sf-dump-public", "sf-dump-protected", "sf-dump-private", ].map(xpathHasClass).join(' or '); var xpathResult = doc.evaluate('.//span[' + classMatches + '][contains(translate(child::text(), ' + xpathString(searchQuery.toUpperCase()) + ', ' + xpathString(searchQuery.toLowerCase()) + '), ' + xpathString(searchQuery.toLowerCase()) + ')]', root, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null); while (node = xpathResult.iterateNext()) state.nodes.push(node); showCurrent(state); }, 400); }); Array.from(search.querySelectorAll('.sf-dump-search-input-next, .sf-dump-search-input-previous')).forEach(function (btn) { addEventListener(btn, 'click', function (e) { e.preventDefault(); -1 !== e.target.className.indexOf('next') ? state.next() : state.previous(); searchInput.focus(); collapseAll(root); showCurrent(state); }) }); addEventListener(root, 'keydown', function (e) { var isSearchActive = !/\bsf-dump-search-hidden\b/.test(search.className); if ((114 === e.keyCode && !isSearchActive) || (isCtrlKey(e) && 70 === e.keyCode)) { /* F3 or CMD/CTRL + F */ e.preventDefault(); search.className = search.className.replace(/\bsf-dump-search-hidden\b/, ''); searchInput.focus(); } else if (isSearchActive) { if (27 === e.keyCode) { /* ESC key */ search.className += ' sf-dump-search-hidden'; e.preventDefault(); resetHighlightedNodes(root); searchInput.value = ''; } else if ( (isCtrlKey(e) && 71 === e.keyCode) /* CMD/CTRL + G */ || 13 === e.keyCode /* Enter */ || 114 === e.keyCode /* F3 */ ) { e.preventDefault(); e.shiftKey ? state.previous() : state.next(); collapseAll(root); showCurrent(state); } } }); } if (0 >= options.maxStringLength) { return; } try { elt = root.querySelectorAll('.sf-dump-str'); len = elt.length; i = 0; t = []; while (i < len) t.push(elt[i++]); len = t.length; for (i = 0; i < len; ++i) { elt = t[i]; s = elt.innerText || elt.textContent; x = s.length - options.maxStringLength; if (0 < x) { h = elt.innerHTML; elt[elt.innerText ? 'innerText' : 'textContent'] = s.substring(0, options.maxStringLength); elt.className += ' sf-dump-str-collapse'; elt.innerHTML = '<span class=sf-dump-str-collapse>'+h+'<a class="sf-dump-ref sf-dump-str-toggle" title="Collapse"> ◀</a></span>'+ '<span class=sf-dump-str-expand>'+elt.innerHTML+'<a class="sf-dump-ref sf-dump-str-toggle" title="'+x+' remaining characters"> ▶</a></span>'; } } } catch (e) { } }; })(document); </script><style> .phpdebugbar pre.sf-dump { display: block; white-space: pre; padding: 5px; overflow: initial !important; } .phpdebugbar pre.sf-dump:after { content: ""; visibility: hidden; display: block; height: 0; clear: both; } .phpdebugbar pre.sf-dump span { display: inline; } .phpdebugbar pre.sf-dump .sf-dump-compact { display: none; } .phpdebugbar pre.sf-dump abbr { text-decoration: none; border: none; cursor: help; } .phpdebugbar pre.sf-dump a { text-decoration: none; cursor: pointer; border: 0; outline: none; color: inherit; } .phpdebugbar pre.sf-dump .sf-dump-ellipsis { display: inline-block; overflow: visible; text-overflow: ellipsis; max-width: 5em; white-space: nowrap; overflow: hidden; vertical-align: top; } .phpdebugbar pre.sf-dump .sf-dump-ellipsis+.sf-dump-ellipsis { max-width: none; } .phpdebugbar pre.sf-dump code { display:inline; padding:0; background:none; } .sf-dump-str-collapse .sf-dump-str-collapse { display: none; } .sf-dump-str-expand .sf-dump-str-expand { display: none; } .sf-dump-public.sf-dump-highlight, .sf-dump-protected.sf-dump-highlight, .sf-dump-private.sf-dump-highlight, .sf-dump-str.sf-dump-highlight, .sf-dump-key.sf-dump-highlight { background: rgba(111, 172, 204, 0.3); border: 1px solid #7DA0B1; border-radius: 3px; } .sf-dump-public.sf-dump-highlight-active, .sf-dump-protected.sf-dump-highlight-active, .sf-dump-private.sf-dump-highlight-active, .sf-dump-str.sf-dump-highlight-active, .sf-dump-key.sf-dump-highlight-active { background: rgba(253, 175, 0, 0.4); border: 1px solid #ffa500; border-radius: 3px; } .phpdebugbar pre.sf-dump .sf-dump-search-hidden { display: none !important; } .phpdebugbar pre.sf-dump .sf-dump-search-wrapper { font-size: 0; white-space: nowrap; margin-bottom: 5px; display: flex; position: -webkit-sticky; position: sticky; top: 5px; } .phpdebugbar pre.sf-dump .sf-dump-search-wrapper > * { vertical-align: top; box-sizing: border-box; height: 21px; font-weight: normal; border-radius: 0; background: #FFF; color: #757575; border: 1px solid #BBB; } .phpdebugbar pre.sf-dump .sf-dump-search-wrapper > input.sf-dump-search-input { padding: 3px; height: 21px; font-size: 12px; border-right: none; border-top-left-radius: 3px; border-bottom-left-radius: 3px; color: #000; min-width: 15px; width: 100%; } .phpdebugbar pre.sf-dump .sf-dump-search-wrapper > .sf-dump-search-input-next, .phpdebugbar pre.sf-dump .sf-dump-search-wrapper > .sf-dump-search-input-previous { background: #F2F2F2; outline: none; border-left: none; font-size: 0; line-height: 0; } .phpdebugbar pre.sf-dump .sf-dump-search-wrapper > .sf-dump-search-input-next { border-top-right-radius: 3px; border-bottom-right-radius: 3px; } .phpdebugbar pre.sf-dump .sf-dump-search-wrapper > .sf-dump-search-input-next > svg, .phpdebugbar pre.sf-dump .sf-dump-search-wrapper > .sf-dump-search-input-previous > svg { pointer-events: none; width: 12px; height: 12px; } .phpdebugbar pre.sf-dump .sf-dump-search-wrapper > .sf-dump-search-count { display: inline-block; padding: 0 5px; margin: 0; border-left: none; line-height: 21px; font-size: 12px; }.phpdebugbar pre.sf-dump, .phpdebugbar pre.sf-dump .sf-dump-default{word-wrap: break-word; white-space: pre-wrap; word-break: normal}.phpdebugbar pre.sf-dump .sf-dump-num{font-weight:bold; color:#1299DA}.phpdebugbar pre.sf-dump .sf-dump-const{font-weight:bold}.phpdebugbar pre.sf-dump .sf-dump-str{font-weight:bold; color:#3A9B26}.phpdebugbar pre.sf-dump .sf-dump-note{color:#1299DA}.phpdebugbar pre.sf-dump .sf-dump-ref{color:#7B7B7B}.phpdebugbar pre.sf-dump .sf-dump-public{color:#000000}.phpdebugbar pre.sf-dump .sf-dump-protected{color:#000000}.phpdebugbar pre.sf-dump .sf-dump-private{color:#000000}.phpdebugbar pre.sf-dump .sf-dump-meta{color:#B729D9}.phpdebugbar pre.sf-dump .sf-dump-key{color:#3A9B26}.phpdebugbar pre.sf-dump .sf-dump-index{color:#1299DA}.phpdebugbar pre.sf-dump .sf-dump-ellipsis{color:#A0A000}.phpdebugbar pre.sf-dump .sf-dump-ns{user-select:none;}</style>
<script type="text/javascript">
var phpdebugbar = new PhpDebugBar.DebugBar();
phpdebugbar.addIndicator("php_version", new PhpDebugBar.DebugBar.Indicator({"icon":"code","tooltip":"Version"}), "right");
phpdebugbar.addTab("messages", new PhpDebugBar.DebugBar.Tab({"icon":"list-alt","title":"Messages", "widget": new PhpDebugBar.Widgets.MessagesWidget()}));
phpdebugbar.addIndicator("time", new PhpDebugBar.DebugBar.Indicator({"icon":"clock-o","tooltip":"Request Duration"}), "right");
phpdebugbar.addTab("timeline", new PhpDebugBar.DebugBar.Tab({"icon":"tasks","title":"Timeline", "widget": new PhpDebugBar.Widgets.TimelineWidget()}));
phpdebugbar.addIndicator("memory", new PhpDebugBar.DebugBar.Indicator({"icon":"cogs","tooltip":"Memory Usage"}), "right");
phpdebugbar.addTab("exceptions", new PhpDebugBar.DebugBar.Tab({"icon":"bug","title":"Exceptions", "widget": new PhpDebugBar.Widgets.ExceptionsWidget()}));
phpdebugbar.addTab("views", new PhpDebugBar.DebugBar.Tab({"icon":"leaf","title":"Views", "widget": new PhpDebugBar.Widgets.TemplatesWidget()}));
phpdebugbar.addTab("route", new PhpDebugBar.DebugBar.Tab({"icon":"share","title":"Route", "widget": new PhpDebugBar.Widgets.VariableListWidget()}));
phpdebugbar.addIndicator("currentroute", new PhpDebugBar.DebugBar.Indicator({"icon":"share","tooltip":"Route"}), "right");
phpdebugbar.addTab("queries", new PhpDebugBar.DebugBar.Tab({"icon":"database","title":"Queries", "widget": new PhpDebugBar.Widgets.LaravelSQLQueriesWidget()}));
phpdebugbar.addTab("emails", new PhpDebugBar.DebugBar.Tab({"icon":"inbox","title":"Mails", "widget": new PhpDebugBar.Widgets.MailsWidget()}));
phpdebugbar.addTab("auth", new PhpDebugBar.DebugBar.Tab({"icon":"lock","title":"Auth", "widget": new PhpDebugBar.Widgets.VariableListWidget()}));
phpdebugbar.addIndicator("auth.name", new PhpDebugBar.DebugBar.Indicator({"icon":"user","tooltip":"Auth status"}), "right");
phpdebugbar.addTab("gate", new PhpDebugBar.DebugBar.Tab({"icon":"list-alt","title":"Gate", "widget": new PhpDebugBar.Widgets.MessagesWidget()}));
phpdebugbar.addTab("session", new PhpDebugBar.DebugBar.Tab({"icon":"archive","title":"Session", "widget": new PhpDebugBar.Widgets.VariableListWidget()}));
phpdebugbar.addTab("request", new PhpDebugBar.DebugBar.Tab({"icon":"tags","title":"Request", "widget": new PhpDebugBar.Widgets.HtmlVariableListWidget()}));
phpdebugbar.setDataMap({
"php_version": ["php.version", ],
"messages": ["messages.messages", []],
"messages:badge": ["messages.count", null],
"time": ["time.duration_str", '0ms'],
"timeline": ["time", {}],
"memory": ["memory.peak_usage_str", '0B'],
"exceptions": ["exceptions.exceptions", []],
"exceptions:badge": ["exceptions.count", null],
"views": ["views", []],
"views:badge": ["views.nb_templates", 0],
"route": ["route", {}],
"currentroute": ["route.uri", ],
"queries": ["queries", []],
"queries:badge": ["queries.nb_statements", 0],
"emails": ["swiftmailer_mails.mails", []],
"emails:badge": ["swiftmailer_mails.count", null],
"auth": ["auth.guards", {}],
"auth.name": ["auth.names", ],
"gate": ["gate.messages", []],
"gate:badge": ["gate.count", null],
"session": ["session", {}],
"request": ["request", {}]
});
phpdebugbar.restoreState();
phpdebugbar.ajaxHandler = new PhpDebugBar.AjaxHandler(phpdebugbar, undefined, true);
phpdebugbar.ajaxHandler.bindToXHR();
phpdebugbar.setOpenHandler(new PhpDebugBar.OpenHandler({"url":"http:\/\/localhost:8000\/_debugbar\/open"}));
phpdebugbar.addDataSet({"__meta":{"id":"Xd39066258b4a2621a0ed4dcd084f5d32","datetime":"2019-06-27 06:31:41","utime":1561617101.172856,"method":"POST","uri":"\/upload","ip":"127.0.0.1"},"php":{"version":"7.3.1","interface":"cli-server"},"messages":{"count":0,"messages":[]},"time":{"start":1561617100.455814,"end":1561617101.172856,"duration":0.7170422077178955,"duration_str":"717.04ms","measures":[{"label":"Booting","start":1561617100.455814,"relative_start":0,"end":1561617100.836836,"relative_end":1561617100.836836,"duration":0.38102221488952637,"duration_str":"381.02ms","params":[],"collector":null},{"label":"Application","start":1561617100.852837,"relative_start":0.39702320098876953,"end":1561617101.172856,"relative_end":0,"duration":0.320019006729126,"duration_str":"320.02ms","params":[],"collector":null}]},"memory":{"peak_usage":12164672,"peak_usage_str":"11.6MB"},"exceptions":{"count":0,"exceptions":[]},"views":{"nb_templates":0,"templates":[]},"route":{"uri":"POST upload","middleware":"web","controller":"App\\Http\\Controllers\\PostController#upload","namespace":"App\\Http\\Controllers","prefix":null,"where":[],"as":"upload","file":"\\app\\Http\\Controllers\\PostController.php:360-468"},"queries":{"nb_statements":1,"nb_failed_statements":0,"accumulated_duration":0.017,"accumulated_duration_str":"17ms","statements":[{"sql":"select * from `users` where `id` = 15 limit 1","type":"query","params":[],"bindings":["15"],"hints":["Use <code>SELECT *<\/code> only if you need all columns from table","<code>LIMIT<\/code> without <code>ORDER BY<\/code> causes non-deterministic results, depending on the query execution plan"],"backtrace":[{"index":15,"namespace":null,"name":"\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\EloquentUserProvider.php","line":52},{"index":16,"namespace":null,"name":"\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\SessionGuard.php","line":131},{"index":17,"namespace":null,"name":"\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\GuardHelpers.php","line":60},{"index":18,"namespace":null,"name":"\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\AuthManager.php","line":292},{"index":19,"namespace":null,"name":"\\vendor\\laravel\\framework\\src\\Illuminate\\Support\\Facades\\Facade.php","line":223},{"index":20,"namespace":null,"name":"\\app\\Http\\Requests\\StorePostRequest.php","line":17},{"index":23,"namespace":null,"name":"\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php","line":87},{"index":24,"namespace":null,"name":"\\vendor\\laravel\\framework\\src\\Illuminate\\
I'm guessing it has do with phpdebugbar
The error messages are stored in the session. To display them you need to access the session in your blade file like {{session('errors')->first('error1')}}.
Take a look at this post for more examples.
I had to remove the phpdebugbar.
\Debugbar::disable();
Related
zooming out of SVG using CSS
I have this SVG of a paperplane, which I want to have inside of a circle. However, when I do the following the SVG is cropped at the edges. The nature of SVG is being scaleable, I have tried fiddling with the properties of the SVG however the problem remains. What should I do to keep this SVG <?xml version="1.0" encoding="utf-8"?> <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 18.7 14.3" style="enable-background:new 0 0 18.7 14.3;" xml:space="preserve"> <style type="text/css"> .st0{fill:#000;} </style> <path class="st0" d="M18.7,0L0.3,4.1l3,3.6L0,9.4l0.5,4.9l5.6-4.1l2.3,1.5L18.7,0z M1.3,4.4L16,1.2L3.8,7.4L1.3,4.4z M10.3,4.7 l-9.3,5.5l-0.2,1.7L0.6,9.7L10.3,4.7z M1.2,13.2l0.4-2.7l2.6-1.6l1.5,1L1.2,13.2z M4.7,8.6l12-7.1l-8.3,9.5L4.7,8.6z"/> </svg> This is my HTML and CSS .choice { background-color: #E0D6AF; border-radius: 50%; height: 200px; width: 200px; margin: 10px auto; transition: transform 0.2s; transform: scale(1); z-index: 10; } <img id="paper" class="choice" value="paper" src="http://www.jerrylow.com/demo/rps/paper.svg" alt="a piece of paper"> </img> Full CSS file .container { display: inline-grid; padding-top:30px; grid-gap: 2px; grid-template-columns: 1fr 1fr 1fr; grid-template-rows: 1fr 1fr 1fr; } #submit { border-radius: 50%; height: 150px; width: 150px; margin: auto; grid-column: 2; grid-row: 2; background-color:#E0D6AF; } #submit:hover { transform: scale(1.3); } .choice { background-color: #E0D6AF; border-radius: 50%; height: 200px; width: 200px; margin: 10px auto; transition: transform 0.2s; transform: scale(1); z-index: 10; } .choice > img:hover { transform: scale(1.1); } #rock{ grid-column: 1; grid-row:1; } #paper{ grid-column: 1; grid-row:2; } #scissor{ grid-column: 1; grid-row:3; } #humanScore > p { padding-top: 80px; text-align: center !important; } #humanScore { grid-column: 2; grid-row: 3; } #computerScore > p { padding-top: 80px; text-align: center !important; } #computerScore { grid-column: 2; grid-row: 1; } #result { margin: auto; width: 150px; height: 150px; border-radius: 50%; grid-column: 3; grid-row: 2; } #keyframes pulse{ 0%{ transform: scale(0); } 100%{ transform: scale(1); } } .resultWin{ background-color:lightgreen; transition: transform 0.2s; transform: scale(1.3); animation-name: pulse; animation-duration: 1s; animation-iteration-count: 1; animation-fill-mode: both; } .resultLoss{ background-color: crimson; transition: transform 0.2s; transform: scale(1.3); animation-name: pulse; animation-duration: 1s; animation-iteration-count: 1; animation-fill-mode: both; } .resultTie{ background-color:goldenrod; transition: transform 0.2s; transform: scale(1.3); animation-name: pulse; animation-duration: 1s; animation-iteration-count: 1; animation-fill-mode: both; } .chosen { filter: brightness(70%) } Full react file - needs a ton of refactoring so difficult to read. import React from 'react'; import './Game.css' class Game extends React.Component { constructor(props) { super(props); this.state = { picked: '', score: { player: 0, computer: 0 }, previousPicks: { rock: 0, scissor: 0, paper: 0 }, result: { result: "", player: "", computer: "" } }; } unmarkImage = () => { if (this.state.picked !== "") { document.querySelector(`#${this.state.picked}`).classList.remove("chosen") } } onClickHandler = (event) => { this.unmarkImage(); document.querySelector(`#${event.target.attributes.value.value}`).classList.add("chosen"); this.setState({ picked: event.target.attributes.value.value }); } onSubmit = () => { if (this.state.picked === "") { alert("pick your weapon, before fighting") return } const self = this; fetch(`/api/play/${this.state.picked}`) .then(function (res) { res.text().then((function (text) { self.setState({ result: JSON.parse('{' + text.replace(/(\w+):(\w+)/g, `"$1":"$2"`) + '}') }) self.updateScore(self.state.result.result); self.updateResult(); self.unmarkImage(); self.updateComputerChoice(); self.updatePreviousPicks(self.state.picked) self.setState({ picked: "" }) })) }) } updateScore = (result) => { let scoreClone = { ...this.state.score } if (result === "win") { scoreClone.player++ this.setState({ score: scoreClone }) } else if (result === "loss") { scoreClone.computer++ this.setState({ score: scoreClone }) } } updatePreviousPicks = (pick) => { let previousPicksClone = { ...this.state.previousPicks } if (pick === "rock") { previousPicksClone.rock++; this.setState({ previousPicks: previousPicksClone }) } else if (pick === "scissor") { previousPicksClone.scissor++; this.setState({ previousPicks: previousPicksClone }) } else { previousPicksClone.paper++; this.setState({ previousPicks: previousPicksClone }) } } onReset = () => { //looks clumsy, but good performance let computerDiv = document.querySelector("#computer") while (computerDiv.firstChild) { computerDiv.removeChild(computerDiv.firstChild); } } updateResult = () => { let result = document.querySelector("#result") if (this.state.result.result === "win") { result.classList.add("resultWin"); } else if (this.state.result.result === "loss") { result.classList.add("resultLoss"); } else { result.classList.add("resultTie"); } } updateComputerChoice = () => { let computerChoice = this.state.result.computer; let result = document.querySelector("#result"); while (result.firstChild) { result.removeChild(result.firstChild); } let answer = document.createElement("img"); let img; if (computerChoice === "rock") { img = document.getElementById("rock").src; } else if (computerChoice === "scissor") { img = document.getElementById("scissor").src; } else { img = document.getElementById("paper").src; } answer.src = img; result.appendChild(answer); } render() { return ( <div className="container"> <img id="rock" className="choice" value="rock" src="resources/rock.svg" alt="a rock" onClick={this.onClickHandler}></img> <img id="paper" className="choice" value="paper" src="resources/paper.svg" alt="a piece of paper" onClick={this.onClickHandler}></img> <img id="scissor" className="choice" value="scissor" src="resources/scissor.svg" alt="a scissor" onClick={this.onClickHandler}></img> <button id="submit" className="waves-effect waves-light btn" onClick={this.onSubmit}>Fight the AI!</button> <div id="humanScore"> <p>You: {this.state.score.player}</p> </div> <div id="computerScore"> <p>Computer: {this.state.score.computer}</p> </div> <div id="result" className=""> </div> </div> ) } } export default Game
To demonstrate #exaneta 's original suggestion, which I can't imagine would have any effect on a grid system, run the snippet below. If that's not what you are trying to accomplish, I'll delete this answer. .choice { background-color: #E0D6AF; border-radius: 50%; height: 200px; width: 200px; margin: 10px auto; transition: transform 0.2s; transform: scale(1); z-index: 10; display: flex; justify-content: center; align-items: center; } .choice > img#paper{ width: 60%; } <div class="choice"> <img id="paper" value="paper" src="http://www.jerrylow.com/demo/rps/paper.svg" alt="a piece of paper" /> </div>
How to optimize display & interactive with large svg image without Lag in FabricJS
I have a fabricJS editor with some large svg files, therefore, when I interactive with ( move / drag ) items on the editor I fill it very lag & heavy. How to optimize using large svg files with fabricJS ? big_image_1.svg: 4.4MB big_image_2.svg: 6.1MB big_image_3.svg: 4.1MB big_image_4.svg: 13.6MB Here is my code: var canvas; var canvasObject = document.getElementById("editorCanvas"); // set canvas equal size with div $(canvasObject).width($("#canvasContainer").width()); $(canvasObject).height($("#canvasContainer").height()); canvas = new fabric.Canvas('editorCanvas', { backgroundColor: 'white', selectionLineWidth: 2, width: $("#canvasContainer").width(), height: $("#canvasContainer").height() }); for (var i = 0; i < 4; i++) { var bigImage = new fabric.Image(); bigImage.left = 10 * (i + 1); bigImage.top = 10 * (i + 1); bigImage["objectCaching"] = true; canvas.add(bigImage); bigImage.setSrc('https://futushigame.firebaseapp.com/big_image/big_image_' + (i + 1) + '.svg', function(imageObject) { imageObject.set('dirty', true); canvas.renderAll(); setObjectCoords(); }); } function setObjectCoords() { canvas.forEachObject(function(object) { object.setCoords(); }); } #canvasContainer { width: 100%; height: 100vh; background-color: gray; } <script src="https://code.jquery.com/jquery-3.3.1.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.4.3/fabric.js"></script> <div id="canvasContainer"> <canvas id="editorCanvas"></canvas> </div> Drag items are filling heavy & lag
You can rewrite needsItsOwnCache from fabric.Image class. var canvasObject = document.getElementById("editorCanvas"); // set canvas equal size with div $(canvasObject).width($("#canvasContainer").width()); $(canvasObject).height($("#canvasContainer").height()); canvas = new fabric.Canvas('editorCanvas', { backgroundColor: 'white', selectionLineWidth: 2, width: $("#canvasContainer").width(), height: $("#canvasContainer").height() }); for (var i = 0; i < 4; i++) { var bigImage = new fabric.Image(); bigImage.left = 10 * (i + 1); bigImage.top = 10 * (i + 1); // bigImage["objectCaching"] = true; bigImage["ownCaching"] = true; // bigImage["clipPath"] = []; canvas.add(bigImage); bigImage.setSrc('https://futushigame.firebaseapp.com/big_image/big_image_' + (i + 1) + '.svg', function(imageObject) { //imageObject.set('dirty', true); canvas.renderAll(); setObjectCoords(); }); } function setObjectCoords() { canvas.forEachObject(function(object) { object.setCoords(); }); } fabric.Image.prototype.needsItsOwnCache = function() { return true } #canvasContainer { width: 100%; height: 100vh; background-color: gray; } <script src="https://code.jquery.com/jquery-3.3.1.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.4.3/fabric.js"></script> <div id="canvasContainer"> <canvas id="editorCanvas"></canvas> </div>
d3js,vuejs, select a subtree
i am a beginner in the JS, Vue and D3 programming but already managed to understand the basics, i think :). So currently i am trying to implement a program which renders a phylogenetical tree using Vue.js and D3.js. Using this example as a start up: https://bl.ocks.org/lorenzopub/02ccce43d708919ca7c0b242fe1c93f2 So far i managed to get my program to open a tree file and to render it properly. Also i can select certain nodes and change their color accordingly. But my problem now is how to select a subtree and change the color of the children nodes. Any help and or hints will be appreciated! Thank you! Here is my code so far: <!DOCTYPE html> <head> <script type="text/javascript" src="VUE/vue.min.js"></script> <script type="text/javascript" src="D3/d3.js"></script> <script>function parseNewick(s) { var ancestors = []; var tree = {}; var tokens = s.split(/\s*(;|\(|\)|,|:)\s*/); for (var i=0; i<tokens.length; i++) { var token = tokens[i]; switch (token) { case '(': // new branchset var subtree = {}; tree.branchset = [subtree]; ancestors.push(tree); tree = subtree; break; case ',': // another branch var subtree = {}; ancestors[ancestors.length-1].branchset.push(subtree); tree = subtree; break; case ')': // optional name next tree = ancestors.pop(); break; case ':': // optional length next break; default: var x = tokens[i-1]; if (x == ')' || x == '(' || x == ',') { tree.name = token; } else if (x == ':') { tree.length = parseFloat(token); } } } return tree; }; </script> <style> .node { opacity: 1; } .node circle { fill: #999; cursor: pointer; } .node text { font: 12px sans-serif; cursor: pointer; } .node--internal circle { fill: #555; } .node--leaf circle { fill: blue; } .node--selected circle { fill: blue } .node--internal text { text-shadow: 0 1px 0 #fff, 0 -1px 0 #fff, 1px 0 0 #fff, -1px 0 0 #fff; } .link { fill: none; stroke: #555; stroke-opacity: 0.4; stroke-width: 1.5px; stroke-dasharray: 1000; } .node:hover { pointer-events: all; stroke: #ff0000; } .node.highlight { fill: red; } .controls { position: fixed; top: 16px; left: 16px; background: #f8f8f8; padding: 0.5rem; display: flex; flex-direction: column; } .controls > * + * { margin-top: 1rem; } label { display: block; } .list-enter-active, .list-leave-active { transition: all 1s; } .list-enter, .list-leave-to /* .list-leave-active for <2.1.8 */ { opacity: 0; transform: translateY(30px); } .line-enter-active, .line-leave-active { transition: all 2s; stroke-dashoffset: 0; } .line-enter, .line-leave-to /* .list-leave-active for <2.1.8 */ { stroke-dashoffset: 1000; } </style> </head> <body> <div id="app"> <div class='controls'> <input type="file" #change="onFileChange"> <label>Search...</label> <input type="text" v-model="search" /> </div> <svg v-bind:width="settings.width" v-bind:height="settings.height"> <!-- LINKS BETWEEN NODES --> <transition-group tag="g" name="line"> <g v-for="link in links" v-bind:key="link.id"> <path class="link" v-bind:style="link.style" v-bind:d="link.d"></path> </g> </transition-group> <!-- LINKS BETWEEN NODES --> <transition-group tag="g" name="list"> <g class="node" v-on:dblclick="selectSubTree(node,index)" v-on:mouseover="mouseOver(node,index)" v-on:click="select(node,index)" v-for="(node, index) in nodes" v-bind:key="node.id" v-bind:style="node.style" v-bind:class="[node.className, {'highlight': node.highlight}]"> <!-- Circles for each node --> <circle v-bind:r="node.r" v-bind:style="node.selCol"></circle> <!-- Finally, text labels --> <text v-bind:dx="node.textpos.x" v-bind:dy="node.textpos.y" v-bind:style="node.textStyle">{{ node.text }}</text> </g> </transition-group> </svg> </div> <script type="text/javascript"> var app = new Vue({ el: '#app', data: function (){ return { treeFile: '', search: '', selected: [], settings: { strokeColor: "#19B5FF", width: 1000, height: 1000 } } }, computed: { root: function(){ var vm = this; if(vm.treeFile){ return vm.tree( d3.hierarchy(parseNewick(vm.treeFile),function(d) { return d.branchset; }) .sum(function(d) { return d.branchset ? 0 : 1; }) .sort(function(a, b) { return (a.value - b.value) || d3.ascending(a.data.length, b.data.length); })); } }, tree: function(){ return d3.tree().size([this.settings.height, this.settings.width - 160]); }, nodes: function(){ var vm = this; if(this.root){ return vm.root.descendants().map(function(d,i) { vm.selected[i]=0; return{ id: d.data.name, index: i, r: 7, className: "node" + (d.children ? " node--internal" : " node--leaf"), text: d.data.name.substring(d.data.name.lastIndexOf(".") +1), highlight: d.data.name.toLowerCase().indexOf(vm.search.toLowerCase()) != -1 && vm.search != "", style: { transform: "translate(" + d.y + "px," + d.x + "px)", }, textpos: { x: d.children ? -10 : 10, y: 3 }, textStyle: { textAnchor: d.children ? "end" : "start" }, children: d.children, selCol: {fill: '#bfbfbf'} }; }); } }, links: function() { var vm = this; if (vm.root) { // here we'll calculate the "d" attribute for each path that is then used in the template where we use "v-for" to loop through all of the links to create <path> elements return vm.root.descendants().slice(1).map(function(d) { return { id: d.data.name, d: "M" + d.y + "," + d.x + "C" + (d.parent.y + 100) + "," + d.x + " " + (d.parent.y + 100) + "," + d.parent.x + " " + d.parent.y + "," + d.parent.x, // here we could of course calculate colors depending on data but for now all links share the same color from the settings object that we can manipulate using UI controls and v-model style: { stroke: vm.settings.strokeColor } }; }); } } }, methods: { onFileChange(e) { var file = e.target.files[0]; var reader = new FileReader(); var vm = this; reader.onloadend = function(e) { vm.treeFile = e.target.result; }; reader.readAsText(file); }, select: function(node, index) { var vm = this; if(this.selected[index] == 0){ this.selected[index]=1; vm.nodes[index].selCol='fill: green'; }else{ this.selected[index]=0; vm.nodes[index].selCol='fill: #bfbfbf'; } vm.$forceUpdate(); }, mouseOver: function (node,index){ // console.log(node.id + " " + node.isSelected); }, selectSubTree: function(node,index){ var vm=this; if(this.selected[index] == 0){ this.selected[index]=1; vm.nodes[index].selCol='fill: green'; }else{ this.selected[index]=0; vm.nodes[index].selCol='fill: #bfbfbf'; } if(node.children){ // console.log(node.id + " HAVE CHILDREN"); // console.log("NC: " + node.children); node.children.forEach(function (d,i){ // this.selected=i; vm.selected[i]=1; vm.nodes[index].selCol='fill: green'; console.log("SELECTING: " + d.data.name + " " + i); console.log(vm.$refs.A); // if(d.isSelected){ // this.selected=i; // console.log("CS :" + this.selected); // } }); }else{ // console.log(node.id + " DONT HAVE CHILDREN"); } vm.$forceUpdate(); } } }) </script> </body>
SASS Color Weight Mixin
I'm trying to create a color weight mixin. The result would be something like Google Material's color weights ( https://material.io/guidelines/style/color.html#color-color-palette ). I'm hoping for a function where I could pass the base color and it would lighten / darken for each weight creating variables and classes for each weight. Take the following manually done weights: $color-blue: #1483ff; $color-blue-100: lighten($color-blue, 30%); $color-blue-200: lighten($color-blue, 20%); $color-blue-400: lighten($color-blue, 10%); $color-blue-500: $color-blue; $color-blue-600: darken($color-blue, 10%); $color-blue-700: darken($color-blue, 20%); $color-blue-800: darken($color-blue, 30%); $color-blue-900: darken($color-blue, 40%); I was experimenting with something like this: $colors: $color-blue-100, $color-blue-200, $color-blue-300; #for $c from 1 through length($colors)-1 { .bg-blue-#{$i} { background: $c; } } but that doesn't work and I still have to manually define the variables.
I took the approach of iterating over a predefined "palette" where the weights and percentages are static as well for colors. All you would have to do going forward is to add/change the colors defined. $colors : ( "blue" : #1483ff, "green" : #4CAF50, "yellow" : #FFEB3B, ); $palette : ( 100 : 40%, 200 : 30%, 300 : 20%, 400 : 10%, 500 : 0, 600 : 10%, 700 : 20%, 800 : 30%, 900 : 40% ); #each $name, $hex in $colors { #each $weight, $percentage in $palette { #if $weight < 500 { .bg-#{"" + $name}-#{$weight} { background-color: lighten($hex, $percentage); } } #else if $weight > 500 { .bg-#{"" + $name}-#{$weight} { background-color: darken($hex, $percentage); } } #else { .bg-#{"" + $name}-#{$weight} { background-color: $hex; } } } } Which compiles to .bg-blue-100 { background-color: #e0efff; } .bg-blue-200 { background-color: #add4ff; } .bg-blue-300 { background-color: #7ab9ff; } .bg-blue-400 { background-color: #479eff; } .bg-blue-500 { background-color: #1483ff; } .bg-blue-600 { background-color: #006ae0; } .bg-blue-700 { background-color: #0052ad; } .bg-blue-800 { background-color: #003a7a; } .bg-blue-900 { background-color: #002247; } .bg-green-100 { background-color: #d9eeda; } .bg-green-200 { background-color: #b5dfb7; } .bg-green-300 { background-color: #92cf94; } .bg-green-400 { background-color: #6ec071; } .bg-green-500 { background-color: #4CAF50; } .bg-green-600 { background-color: #3d8b40; } .bg-green-700 { background-color: #2d682f; } .bg-green-800 { background-color: #1e441f; } .bg-green-900 { background-color: #0e210f; } .bg-yellow-100 { background-color: white; } .bg-yellow-200 { background-color: #fffbd4; } .bg-yellow-300 { background-color: #fff5a1; } .bg-yellow-400 { background-color: #fff06e; } .bg-yellow-500 { background-color: #FFEB3B; } .bg-yellow-600 { background-color: #ffe608; } .bg-yellow-700 { background-color: #d4be00; } .bg-yellow-800 { background-color: #a19100; } .bg-yellow-900 { background-color: #6e6300; }
This should do it and no variables to define. You can see the output on sassmeister. #mixin color-weight ($class, $base-color, $weight: 4) { $bg-color: null; #for $i from 1 through 8 { #if $i < 4 { $weight: $weight - 1; $bg-color: lighten($base-color, $weight * 10%); } #else if $i == 4 { $weight: 0; $bg-color: $base-color; } #else { $weight: $weight + 1; $bg-color: darken($base-color, $weight * 10%); } .#{$class}-#{$i} { background-color: $bg-color; } } } #include color-weight(bg-blue, #1483ff); #include color-weight(mad, red);
Parallax effect - calculate child offset to parent on scroll
I'm trying to create a parallax effect whereby an absolutely positioned child element should move at a rate slower than it's parent on scroll. The child will always be 130% height of the parent but the parent can be any height: HTML: <div class="parallax-window lg"> <div class="parallax-image image-1"></div> <div class="parallax-content">Hello World</div> </div> <div class="parallax-window"> <div class="parallax-image image-2"></div> <div class="parallax-content">Hello World</div> </div> CSS: .parallax-window { min-height: 300px; position: relative; overflow: hidden; } .parallax-window.lg { min-height: 600px; } .parallax-image { position: absolute; top: 0; left: 0; width: 100%; height: 130%; background-size: cover; background-repeat: no-repeat; background-position: 50% 50%; transform: translate3d(0, 0, 0); z-index: -1; } .image-1 { background-image: url(https://i.ytimg.com/vi/TbC-vUPMR7k/maxresdefault.jpg); } .image-2 { background-image: url(https://i.ytimg.com/vi/xi5-YrAEChc/maxresdefault.jpg); } I have a formula to move the image but my maths is clearly way off: var win = $(window), win_h = win.height(), parallaxers = $('.parallax-window'); function scroll_events() { var win_top = win.scrollTop(), win_btm = win_top + win_h; parallaxers.each(function() { var cont = $(this), cont_top = cont.offset().top, cont_h = cont.height(), cont_btm = cont_top + cont_h, para = cont.find('.parallax-image'), para_h = Math.round(cont_h * 1.3); if (cont_btm > win_top && cont_top <= win_btm) { var diff = (win_h - cont_h) / (win_h - para_h), value = -Math.round((win_top * diff)); // para.css('transform', 'translate3d(0,' + value*-1 + 'px, 0)'); para.css('top', value + 'px'); } }); } The images move but not at the correct rate. The image should be in line with the top of the parent when the element first comes into the viewport. Then after scrolling, the bottom of the image should be in line with the bottom of the parent when it reaches the top of the viewport. Any help would be massively appreciated! FIDDLE (https://jsfiddle.net/8dwLwgy7/1/)
I figured this out. For anyone stumbling on this in the future - the trick was to replace the window scrolled value with the remainder of the window scrolled amount minus the element's offset top, minus the height of the element. Then calculate the speed by dividing the difference between the container height and the element height with largest of either the window and the container: // Wrong: // value = -Math.round((win_top * diff)); // Right: var diff = elem_h - cont_h, max = Math.max(cont_h, win_h), speed = diff / max, cont_scrolled = win_top - cont_top - cont_h, value = Math.round(cont_scrolled * speed); para.css('top', value + 'px'); Full working code: (function() { var lastTime = 0; var vendors = ['ms', 'moz', 'webkit', 'o']; for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame']; window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame']; } if (!window.requestAnimationFrame) window.requestAnimationFrame = function(callback, element) { var currTime = new Date().getTime(); var timeToCall = Math.max(0, 16 - (currTime - lastTime)); var id = window.setTimeout(function() { callback(currTime + timeToCall); }, timeToCall); lastTime = currTime + timeToCall; return id; }; if (!window.cancelAnimationFrame) window.cancelAnimationFrame = function(id) { clearTimeout(id); }; }()); (function($) { var win = $(window), win_h = win.height(); parallaxers = $('.parallax-window'), parallax_objs = [], scroll_busy = false; function init_parallax() { win_h = win.height(); parallax_objs = []; parallaxers.each(function() { var cont = $(this), elem = cont.find('.parallax-image'), cont_top = cont.offset().top, cont_h = cont.height(), elem_h = Math.round(cont_h * 1.3), diff = elem_h - cont_h, max = Math.max(cont_h, win_h), speed = diff / max, parallaxer = { cont_top: cont_top, cont_h: cont_h, elem: elem, speed: speed }; parallax_objs.push(parallaxer); }); } function on_scroll() { if (!scroll_busy) { scroll_busy = true; window.requestAnimationFrame(init_scroll); } } function init_scroll() { scroll_events() scroll_busy = false; } function scroll_events() { var win_top = win.scrollTop(), win_btm = win_top + win_h; $.each(parallax_objs, function(i, para) { cont_btm = para.cont_top + para.cont_h; if( cont_btm > win_top && para.cont_top <= win_btm ) { var cont_scrolled = win_top - para.cont_top - para.cont_h, value = Math.round(cont_scrolled * para.speed); para.elem.css('top', value + 'px'); } }); } $(document).ready(function() { init_parallax(); win.resize(init_parallax); scroll_events(); win.scroll(on_scroll); }); })(jQuery); .parallax-window { min-height: 300px; position: relative; overflow: hidden; } .parallax-window.lg { min-height: 600px; } .parallax-image { position: absolute; top: 0; left: 0; width: 100%; height: 130%; background-size: cover; background-repeat: no-repeat; background-position: 50% 50%; transform: translate3d(0, 0, 0); z-index: -1; } .image-1 { background-image: url(https://i.ytimg.com/vi/TbC-vUPMR7k/maxresdefault.jpg); } .image-2 { background-image: url(https://i.ytimg.com/vi/xi5-YrAEChc/maxresdefault.jpg); } .parallax-content { position: absolute; top: 50%; left: 0; width: 100%; text-align: center; font-family: arial, sans-serif; font-size: 60px; color: #fff; transform: translateY(-50%); } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <div class="parallax-window lg"> <div class="parallax-image image-1"></div> <div class="parallax-content">Hello World</div> </div> <div class="parallax-window"> <div class="parallax-image image-2"></div> <div class="parallax-content">Hello World</div> </div> <div class="parallax-window lg"> <div class="parallax-image image-1"></div> <div class="parallax-content">Hello World</div> </div> <div class="parallax-window"> <div class="parallax-image image-2"></div> <div class="parallax-content">Hello World</div> </div> <div class="parallax-window lg"> <div class="parallax-image image-1"></div> <div class="parallax-content">Hello World</div> </div> Updated Fiddle: https://jsfiddle.net/8dwLwgy7/2/