-2

I'm trying to see if it's possible to conditionally move an html element using JS?

The idea is if I have an image that's returned I'd like it to be on the same line as the title and the title moved to the right (allocating space for the img on the left). Is it possible?

would it be preferably done in a handlebars helper method or the standard js file?

I was thinking something along the lines of

//thumbnail conditional moving title if exists
if(results.thumbnail != 0) {
    //do something here
}
Tolga Evcimen
  • 7,112
  • 11
  • 58
  • 91
Davington III
  • 107
  • 12

1 Answers1

1

Im not sure if i understand you question correctly.

Is this somewhat in the right direction?

Anyway, your information is very vague. And i think the logic in this script is in somewhat the right direction. Modify it to your needs.

// DUMMY RESPONSE FROM "API"
var response = [{
  title: "Hello World, with image",
  image: "http://placehold.it/200/200"
}, {
  title: "Hello World, no image",
  image: ""
}]


//JUST TO VARY THE RESULT A BIT, SELECT A RANDOM POST FROM THE RESPONSE.
var post = response[getRandomInt(0, 1)];

// SELECT THE FIRST (AND IN THIS SCRIPT, ONLY) H1 TAG
var elem = document.getElementsByTagName("h1")[0];

// SET THE TEXT OF THE H1 TAG TO BE EQUAL THE POST TITLE
elem.innerText = post.title;

// IF THE "IMAGE" PROPERTY OF THE RESPONSE CONTAINS A STRING/VALUE THAT HAS
// A LENGTH, BIGGER THEN 0 - WE ASSUME THERE IS A LINK IN THERE TO THE IMG.
if (post.image.length > 0) {

  // ADD THE IMG HTML, AND APPEND THE CURRENT TEXT OF THE ELEMENT
  // THIS ALL HAPPENS INSIDE THE "H1" ELEMENT. 

  elem.innerHTML = '<img src="' + post.image + '" /> ' + elem.innerText;
}



/**
 * Returns a random integer between min (inclusive) and max (inclusive)
 * Using Math.round() will give you a non-uniform distribution!
 * Credits: http://stackoverflow.com/questions/1527803/generating-random-numbers-in-javascript-in-a-specific-range
 */
function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
<h1></h1>

This shows one of several ways to add an image in/next to your title.

Click RUN several times to show how it reacts to responses without an image.

If this doesnt answer you question, then you need to put a better description in your post, with more information. Maybe a JSFiddle with expected result.

Christer
  • 1,651
  • 1
  • 17
  • 34
  • This does answer my question thank you for the suggestion, my question was very vague because I was thinking conditionally using html elements wasn't a thing that could be done so I was overly tentative about the information I added, apologies for that but this is a great suggestion thank you :) – Davington III Dec 10 '15 at 10:08
  • Added comments - might be easier to understand whats going on :) – Christer Dec 10 '15 at 10:10